luasocket 的 settimeout() 如何工作?

我有以下的代码:

” function Server:run() print("Running.") self.running = true while self.running do if self.client == nil then self.client = self.socket:accept() print("Client connected.") self.client:settimeout(10) end local line, err = self.client:receive() if err then print("Error: " .. err) elseif line == "quit" then print("Quitting.") self.client:close() self.running = false else print("Received: " .. line) end end self:terminate() end “

我期望当self.client:receive()被调用时,服务器将等待10秒或直到它有一条消息,然后继续。

然而,这不是我所体验到的行为。无论超时设置的值是什么,服务器都会立即生成超时错误,并且根本不等待来自客户端的消息。

我怀疑我误解了什么。任何见解将不胜感激。谢谢。


完整的代码在这里:

服务器:http://pastie.org/9659701

主要的:http://pastie.org/9659703


点赞
用户1442917
用户1442917

这段代码在我的环境下(Windows,LuaJIT 2.0.2,luasocket 3.0-rc1)按预期工作; 我在以下独立脚本中进行了测试:

local socket = require "socket"
local server = assert(socket.bind("*", 3333))
local client = server:accept()
print("accepted connection; waiting for data...")
client:settimeout(10)
local start = os.time()
local line, err, partial = client:receive("*l")
if line then
  print(("received '%s'; echoing back..."):format(line))
  client:send(line.."\n")
else
  print(("received error '%s' after %.2f seconds."):format(err, os.time()-start))
end
client:close()

您可以运行telnet localhost 3333并应看到“accepted connection; waiting for data...”; 如果我不发送任何内容,则会收到“received error 'timeout' after 10.00 seconds.”,这正是我所期望的。

我会检查是否存在逻辑错误,并且在您的情况下self.client从未为nil,您不会调用settimeout。如果这仍然没有帮助,请创建一个我们可以使用love2d运行的独立示例(例如,我没有看到您在哪里调用bind)。

2014-10-17 19:25:21