2

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

4

1 回答 1

0

最好有一个专用线程从每个套接字读取传入数据。当发生意外的套接字断开连接时(例如客户端网络掉线或崩溃),套接字将抛出异常。然后您可以捕获异常,然后关闭套接字连接并干净地结束线程,同时保持其他套接字运行。

我从本教程中学习了 TCP/IP 通信。

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

作者很好地解释了他的实现。值得借鉴。您可以参考它来重写您自己的库。

于 2015-09-08T02:14:10.973 回答