Alexander Knoth
Alexander Knoth

Reputation: 147

Determine socket connection state in async server

Is it possible to check if the client socket is keeping connection alive at the moment? I use multithread server that use AsyncCallBack operations. There is a lot of similar questions about this issue and I've read about Socket.Poll method - everything doesn't work properly.

Tried to apply this sample:

    bool IsConnectedAviable(Socket s)
    {
        try
        {
            if (s != null && s.Connected)
            {
                if (s.Poll(0, SelectMode.SelectRead))
                {
                    byte[] buff = new byte[1];
                    if (s.Receive(buff, SocketFlags.Peek) == 0)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }

                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }

Thanks in advance! :)

Upvotes: 1

Views: 1528

Answers (2)

dtb
dtb

Reputation: 217313

If you receive something from the other end, you know the connection is still alive. If you don't receive anything from the other end for a while, the only way to determine if the connection is still alive is by sending something.

Upvotes: 2

Roman Starkov
Roman Starkov

Reputation: 61412

I think you have to change the way you think about Sockets. Simplifying a bit, they have two states: "definitely disconnected" and "maybe disconnected". Code accordingly. In the "maybe disconnected" state the best you can do is try to send data. If you're using TCP, and the delivery was successful, nothing will happen. If not, you'll get an exception – but only seconds later, after TCP has attempted its retries.

This is a necessary evil of the physical world: the train you're on might have just entered a tunnel, and if the method said "yes, I am connected" that would actually be a lie.

Upvotes: 0

Related Questions