How to check socket is closed or not in luasocket library?

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

And I can’t find any method for detecting a socket that is closed or not in its reference guide, except that just try to read the data from it (it will return zero and close the line when this is called).

My code is as follows:

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
+5
source share
1 answer

except that just try reading the data from it (it will return nil and string "close" when calling this).

I do not know another method. Why doesn't it check the result of reading a socket?

setimeout, , closed (not close). , .

+1

All Articles