【发布时间】:2017-05-29 15:09:08
【问题描述】:
我正在尝试使用服务器套接字实现一个脚本,该脚本还将定期轮询来自多个传感器的数据(即每分钟的第 59 秒)。我不想将数据序列化到磁盘,而是将其保存在一个表中,当轮询时套接字将响应该表。 这是一些代码草图来说明我正在尝试做的事情(我没有包含访问此服务器的客户端代码,但那部分是可以的)
#!/usr/bin/env lua
local socket = require("socket")
local server = assert(socket.bind("*", 0))
local ip, port = server:getsockname()
local data = {}
local count = 1
local function pollSensors()
-- I do the sensor polling here and add to table e.g os.time()
table.insert(data, os.time() .."\t" .. tostring(count))
count = count + 1
end
while true do
local client = server:accept()
client:settimeout(2)
local line, err = client:receive()
-- I do process the received line to determine the response
-- for illustration I'll just send the number of items in the table
if not err then client:send("Records: " ..table.getn(data) .. "\n") end
client:close()
if os.time().sec == 59 then
pollSensors()
end
end
我担心服务器有时会阻塞,因此我会错过第 59 秒。
这是实现此功能的好方法,还是有(更简单)更好的方法(例如使用协程)?如果协程会更好,我该如何在我的场景中实现它们?
【问题讨论】:
-
与您的问题无关,但不推荐使用
table.getn。 -
@hjpotter92 - 感谢您的评论,尽管我在这里使用它只是为了说明,并不打算在我的生产代码中使用它。不过,很高兴知道。