Search code examples
c#socketsoptimizationserver

C# sockets How can I handle unplanned disconnections on socket servers?


I am building a socket server in C#, and i have an issue with unplanned sockets disconnects. For now, i am handling this like that:

private List<TCPClient> _acceptedClientsList = new List<TCPClient>();
public void checkIfStillConnected()
{
    while (true)
    {
        lock (_sync)
        {
            for (int i = 0; i < _acceptedClientsList.Count(); ++i)
            {
                if (_acceptedClientsList[i].Client.Client.Poll(10, SelectMode.SelectRead) == true && (_acceptedClientsList[i]).Client.Client.Available == 0) // 5000 is the time to wait for a response, in microseconds.
                {
                    NHDatabaseHandler dbHandler = new NHDatabaseHandler();
                    dbHandler.Init();
                    if (_acceptedClientsList[i].isVoipClient == true)
                    {
                        dbHandler.UpdateUserStatus(_acceptedClientsList[i].UserName, EStatus.Offline);
                    }
                    RemoveClient(i); // this function removes the selected client at i from the acceptedClientsList
                    i--;
                }
            }
        }
    }
}

But this is not optimized at all. This is a thread who checks every sockets status with the socket.poll, every time, infinitely...

I don't know if it's the best thing to do... It looks like it's heavy and weird. Does anyone has an idea?

Thanks


Solution

  • It is best to have one dedicated thread to read incoming data from each socket. When unplanned socket disconnection occurs (for e.g. the client side network drops out or crashes), the socket will throw an exception. You can then catch exception, then close the socket connection and end the thread cleanly while keeping other socket running.

    I learnt the TCP/IP communication from this tutorial.

    http://www.codeproject.com/Articles/155282/TCP-Server-Client-Communication-Implementation

    The author explains his implementation very well. It's worth learning from. You can reference it to rewrite your own library.