Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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).

My code looks like this:

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
like image 766
moligaloo Avatar asked Apr 17 '13 07:04

moligaloo


People also ask

How do I check if my socket is closed?

If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

What is Lua socket?

LuaSocket is a Lua extension library composed of two parts: a set of C modules that provide support for the TCP and UDP transport layers, and. a set of Lua modules that provide functions commonly needed by applications that deal with the Internet.


1 Answers

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?

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.

like image 129
Paul Kulchenko Avatar answered Nov 09 '22 10:11

Paul Kulchenko