首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LuaSocket服务器:接受()超时(TCP)

LuaSocket服务器:接受()超时(TCP)
EN

Stack Overflow用户
提问于 2017-02-24 18:03:50
回答 1查看 18.6K关注 0票数 6

问题

LuaSocket 引言之后,我设法使服务器运行。我还设法从客户端连接。但是,我注意到服务器脚本会冻结,直到server:accept()获得连接。

Research

LuaSocket 参考文献指定:

使用settimeout方法或接受可能会阻塞,直到另一个客户端出现。

这甚至包括在示例代码中。但是,client:settimeout(10)是在local client = server:accept()之后调用的,因此脚本在到达此点之前就会被阻塞。

我读到可以通过多线程来解决这个问题,但这似乎有点夸张。

问题

  1. 如何使服务器脚本停止等待连接并继续前进?
  2. 如何防止client:receive() (服务器端)和tcp:receive() (客户端)(或client:settimeout(10)负责处理)出现类似的问题?

服务器(来自LuaSocket 引言)

代码语言:javascript
复制
-- 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

客户端(跟随这个答案)

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-24 18:34:57

您应该能够在调用服务器:timeout()之前使用server:accept()

代码语言:javascript
复制
server:settimeout(2)
local client, err = server:accept()
print(client, err)

如果在2秒内没有收到任何请求,这将为我打印nil timeout

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42445423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档