LuaSocket server:accept() timeout (TCP)
问题
按照
研究
Use the settimeout method or accept might block until another client shows up.
甚至包括在示例代码中。 但是,在
我读到可以通过多线程解决此问题,但这似乎有点夸张。
问题
码
服务器(来自
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | -- 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 .."\ ") end -- done with client, close the object client:close() end |
客户(遵循此答案)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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\ "); while true do local s, status, partial = tcp:receive() print(s or partial) if status =="closed" then break end end tcp:close() |
您应该能够在调用
1 2 3 | server:settimeout(2) local client, err = server:accept() print(client, err) |
如果2秒钟内没有请求,这将为我打印