2014-10-17 416 views
3

我有以下代码: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:接收()被调用时,服务器会等待10秒,直到它有一个消息,然后继续在它的途中。

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

我怀疑我误解了一些东西。任何见解都会被认可。谢谢。


全部代码在这里:

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

主:http://pastie.org/9659703


回答

0

如预期中的代码对我的作品(在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和应该看到“接受的连接;等待数据...”;如果我不发送任何东西,10.00秒后我会收到“收到错误”超时。“,这正是我所期望的。

我会检查是否有逻辑错误,self.client从来没有nil你的情况,你不叫settimeout。如果这仍然没有帮助,请创建一个可以使用love2d运行的独立示例(例如,我看不到您拨打bind的位置)。

+0

使用完整的代码进行编辑。 – 2014-10-18 20:24:40