Coldairarrow / DotNettySocket

An Easy Socket(TcpSocket,WebSocket,UdpSocket) Framework Based On DotNetty
Apache License 2.0
272 stars 72 forks source link

服务器关闭前移除所有连接时关闭各客户端连接时不执行OnConnectionClose事件 #6

Open Wenchel opened 3 years ago

Wenchel commented 3 years ago

感谢大佬的封装,有一个疑问:

foreach (var item in tcpServer.GetAllConnections())
            {
                item.Close();
                tcpServer.RemoveConnection(item);
            }
            tcpServer.Close();

item在Close()时不执行ConnectionClose 但是,当有新客户端建立连接时,通过connection.Close()是可以触发ConnectionClose事件的:

.OnNewConnection((server, connection) =>
                {
                    var clientAddress = connection.ClientAddress.Address.MapToIPv4().ToString();
                    var clientPort = connection.ClientAddress.Port;
                    connection.ConnectionName = $"{clientAddress}:{clientPort}";
                    if (!config.ClientsList.Contains(clientAddress))
                        connection.Close();
                    else
                    {
                        //{clientAddress}:{clientPort}连接成功
                    }
                })
                .OnConnectionClose((server, connection) =>
                {
                    //{connection.ConnectionName}断开连接
                })

上述代码在有新连接时判断是否在名单中,不在名单中则断开连接,此时触发OnConnectionClose