如何通过luasocket库中的方法来确认一个套接字是否已经被彻底关闭?

2026-04-01 20:221阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计370个文字,预计阅读时间需要2分钟。

如何通过luasocket库中的方法来确认一个套接字是否已经被彻底关闭?

我正在用Lua编写服务器,网络层基于LuaSocket。在参考手册中找不到检测套接字是否已关闭的方法,只能通过尝试从中读取数据(在调用时它将返回nil和字符串'close')来间接判断。

如何通过luasocket库中的方法来确认一个套接字是否已经被彻底关闭?

我正在使用Lua编程语言编写服务器,网络层基于 LuaSocket.

我在参考手册中找不到任何方法来检测套接字是否已关闭,只是尝试从中读取数据(在调用时它将返回nil和字符串’close’).

我的代码看起来像这样:

local socket = require 'socket' local server = socket.tcp() local port = 9527 server:bind('*', port) local status, errorMessage = server:listen() if status == 1 then printf('Server is launched successfully on port %u', port) else printf('Server listen failed, error message is %s', errorMessage) return end local sockets = {server} while true do local results = socket.select(sockets) for _, sock in ipairs(results) do if sock == server then local s = server:accept() callback('Connected', s) table.insert(sockets, s) printf('%s connected', s:getsockname()) else -- trying to detect socket is closed if sock:isClosed() then callback('Disconnected', sock) for i, s in ipairs(sockets) do if s == sock then table.remove(sockets, i) break end end printf('%s disconnected', sock:getsockname()) else callback('ReadyRead', sock) end end end end

except by just try to read data from it (it will return nil and string ‘close’ when calling that).

我不知道任何其他方法.为什么不检查读取套接字的结果?

您需要使用settimeout使调用无阻塞,并检查为关闭(不关闭)返回的错误.您可以读取一个字节并存储它,或者您可以尝试读取零字节.

本文共计370个文字,预计阅读时间需要2分钟。

如何通过luasocket库中的方法来确认一个套接字是否已经被彻底关闭?

我正在用Lua编写服务器,网络层基于LuaSocket。在参考手册中找不到检测套接字是否已关闭的方法,只能通过尝试从中读取数据(在调用时它将返回nil和字符串'close')来间接判断。

如何通过luasocket库中的方法来确认一个套接字是否已经被彻底关闭?

我正在使用Lua编程语言编写服务器,网络层基于 LuaSocket.

我在参考手册中找不到任何方法来检测套接字是否已关闭,只是尝试从中读取数据(在调用时它将返回nil和字符串’close’).

我的代码看起来像这样:

local socket = require 'socket' local server = socket.tcp() local port = 9527 server:bind('*', port) local status, errorMessage = server:listen() if status == 1 then printf('Server is launched successfully on port %u', port) else printf('Server listen failed, error message is %s', errorMessage) return end local sockets = {server} while true do local results = socket.select(sockets) for _, sock in ipairs(results) do if sock == server then local s = server:accept() callback('Connected', s) table.insert(sockets, s) printf('%s connected', s:getsockname()) else -- trying to detect socket is closed if sock:isClosed() then callback('Disconnected', sock) for i, s in ipairs(sockets) do if s == sock then table.remove(sockets, i) break end end printf('%s disconnected', sock:getsockname()) else callback('ReadyRead', sock) end end end end

except by just try to read data from it (it will return nil and string ‘close’ when calling that).

我不知道任何其他方法.为什么不检查读取套接字的结果?

您需要使用settimeout使调用无阻塞,并检查为关闭(不关闭)返回的错误.您可以读取一个字节并存储它,或者您可以尝试读取零字节.