我想实现一个脚本与服务器套接字,它也将周期性地轮询来自多个传感器(即在每分钟的第59秒)的数据。我不想将数据序列化到磁盘,而是将它保存在一个表中,该表将在轮询时响应。 下面是一些素描的代码来说明什么,我试图做(我还没有列入访问该服务器的客户端代码,但这部分是OK)Lua - 套接字与其他事件的定时器接收
#!/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
我担心的是,服务器有时可能会(s)挡,因此我会错过第59秒。
这是一个很好的方法来实现这个或有一个(更简单)更好的方式来做到这一点(说使用协程)?如果协程更好,我如何为我的场景实现它们?
与您的问题无关,但'table.getn'已弃用。 – hjpotter92
@ hjpotter92 - 感谢您的评论,尽管我在此仅用于说明,并不打算在我的生产代码中使用它。不过,很高兴知道。 – Nepaluz