C# 套接字 如何处理套接字服务器上的计划外断开连接?

标签 c# sockets optimization server disconnected

我正在用 C# 构建套接字服务器,但我遇到了计划外套接字断开连接的问题。 现在,我是这样处理的:

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--;
                }
            }
        }
    }
}

但这根本没有优化。这是一个使用 socket.poll 检查每个套接字状态的线程,每次,无限...

我不知道这样做是不是最好的……看起来又重又怪。 有人有想法吗?

谢谢

最佳答案

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

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

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

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

关于C# 套接字 如何处理套接字服务器上的计划外断开连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445499/

相关文章:

c# - 为什么 typeof(Object[,][]).Name 等于 "Object[][,]"?

c# - 这是“切换” boolean 值的可接受方法吗?

c - 不工作 SSL 服务器

c# - 客户端套接字未获取.NET中的响应字节

algorithm - 查找乘积大于总和的对

javascript - 与使用 $.each 相比,将监听器添加到 jQuery 类集的效率

c# - n 休眠。动态选择需要添加到结果集中的引用

c# - REST 超媒体 URI 更改基于 Web API 中的上下文 (HATEOAS)

c - TCP 客户端-服务器 "bad address"错误(在 C 中)

python - 为什么我的 NLTK 函数在处理 DataFrame 时速度很慢?