2
继LuaSocket
Introduction我设法让服务器运行。我也设法从客户端连接。不过,我注意到,服务器脚本冻结,直到server:accept()
获得连接。
研究
LuaSocket
Reference规定:
使用的setTimeout方法或接受可能被阻塞,直到另一个客户端显示出来。
这甚至包括在示例代码中。但是,在local client = server:accept()
之后调用client:settimeout(10)
,因此脚本在达到此点之前会被阻止。
我读过这可以通过多线程解决,但这似乎是一个夸大。
问题
- 你如何导致服务器脚本停止等待连接,继续前进?
- 如何防范
client:receive()
(服务器端)和tcp:receive()
(客户端)(或client:settimeout(10)
负责)类似的问题?
代码
服务器(从LuaSocket
Introduction)
-- 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()