如何在luasocket库中检查套接字是否关闭? [英] How to check a socket is closed or not in luasocket library?

查看:439
本文介绍了如何在luasocket库中检查套接字是否关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a server using Lua programming language, and the network layer is based on LuaSocket.

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

And I cannot find any method to detect a socket is closed or not in its reference manual except by just try to read data from it(it will return nil and string 'close' when calling that).

我的代码如下:

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

推荐答案

除了只是尝试从中读取数据(调用它时将返回nil和字符串"close").

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

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

I'm not aware of any other method. Why doesn't checking the result from reading a socket work for you?

您需要使用settimeout来使呼叫成为非阻塞状态,并检查为closed(不是close)返回的错误.您可以读取一个字节并进行存储,也可以尝试读取零字节.

You need to use settimeout to make the call non-blocking and check the error returned for closed (not close). You can read one byte and store it or you can try reading zero bytes.

这篇关于如何在luasocket库中检查套接字是否关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆