sách gpt4 ai đã đi

sockets - 如何检查 luasocket 库中的套接字是否关闭?

In lại 作者:可可西里 更新时间:2023-11-01 02:32:12 25 4
mua khóa gpt4 Nike

我正在用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)
khác
printf('Server listen failed, error message is %s', errorMessage)
trở lại
kết thúc

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())
khác
-- 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)
phá vỡ
kết thúc
kết thúc

printf('%s disconnected', sock:getsockname())
khác
callback('ReadyRead', sock)
kết thúc
kết thúc
kết thúc
kết thúc

1 Câu trả lời

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

我不知道任何其他方法。为什么检查读取套接字的结果对您不起作用?

您需要使用 settimeout 使调用成为非阻塞的,并检查为 closed(còn hơn là close)返回的错误。您可以读取一个字节并存储它,也可以尝试读取零字节。

关于sockets - 如何检查 luasocket 库中的套接字是否关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16054394/

25 4 0
可可西里
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com