2017-02-24 170 views
2

問題LuaSocket服務器:接受()超時(TCP)

LuaSocketIntroduction我設法讓服務器運行。我也設法從客戶端連接。不過,我注意到,服務器腳本凍結,直到server:accept()獲得連接。

研究

LuaSocketReference規定:

使用的setTimeout方法或接受可能被阻塞,直到另一個客戶端顯示出來。

這甚至包括在示例代碼中。但是,在local client = server:accept()之後調用client:settimeout(10),因此腳本在達到此點之前會被阻止。

我讀過這可以通過多線程解決,但這似乎是一個誇大。

問題

  1. 你如何導致服務器腳本停止等待連接,繼續前進?
  2. 如何防範client:receive()(服務器端)和tcp:receive()(客戶端)(或client:settimeout(10)負責)類似的問題?

代碼

服務器(從LuaSocketIntroduction

-- load namespace 
local socket = require("socket") 
-- create a TCP socket and bind it to the local host, at any port 
local server = assert(socket.bind("*", 0)) 
-- find out which port the OS chose for us 
local ip, port = server:getsockname() 
-- print a message informing what's up 
print("Please telnet to localhost on port " .. port) 
print("After connecting, you have 10s to enter a line to be echoed") 
-- loop forever waiting for clients 
while 1 do 
    -- wait for a connection from any client 
    local client = server:accept() 
    -- make sure we don't block waiting for this client's line 
    client:settimeout(10) 
    -- receive the line 
    local line, err = client:receive() 
    -- if there was no error, send it back to the client 
    if not err then client:send(line .. "\n") end 
    -- done with client, close the object 
    client:close() 
end 

客戶端(如下this answer

local host, port = "127.0.0.1", 100 
local socket = require("socket") 
local tcp = assert(socket.tcp()) 

tcp:connect(host, port); 
--note the newline below 
tcp:send("hello world\n"); 

while true do 
    local s, status, partial = tcp:receive() 
    print(s or partial) 
    if status == "closed" then break end 
end 
tcp:close() 

回答

1

你應該能夠調用前使用:

server:settimeout(2) 
local client, err = server:accept() 
print(client, err) 

這將打印nil timeout對我來說,如果沒有請求到達2秒。