/// <summary> /// Releases the managed and unmanaged resources used by the <see cref="AsyncTcpClient"/>. /// Closes the connection to the remote host and disabled automatic reconnecting. /// </summary> public void Dispose() { AutoReconnect = false; tcpClient?.Dispose(); HeartBeatTimer?.Dispose(); stream = null; }
public async Task RunAsync() { if (tcpListener != null) { if (TCPExceptionEvent != null) { TCPExceptionEvent(new InvalidOperationException("ERROR10029侦听器已在运行")); } return; } if (Port <= 0 || Port > ushort.MaxValue) { if (TCPExceptionEvent != null) { TCPExceptionEvent(new ArgumentOutOfRangeException(nameof(Port))); } return; } isStopped = false; closeClients = false; tcpListener = new TcpListener(IPAddress, Port); tcpListener.Start(); Message?.Invoke(this, new AsyncTcpEventArgs("等待连接")); clients = new ConcurrentDictionary <TcpClientEx, bool>(); // bool is dummy, never regarded var clientTasks = new List <Task>(); try { while (true) { TcpClient tc; TcpClientEx tcpClient = null;; try { tc = await tcpListener.AcceptTcpClientAsync(); tcpClient = new TcpClientEx(tc); tcpClient.ReceiveTimeout = TcpPackConfig.ReceiveTimeout; tcpClient.SendTimeout = TcpPackConfig.SendTimeout; tcpClient.SendBufferSize = TcpPackConfig.SendBufferSize; tcpClient.ReceiveBufferSize = TcpPackConfig.ReceiveBufferSize; } catch (ObjectDisposedException) when(isStopped) { // Listener was stopped break; } var endpoint = tcpClient.Client.RemoteEndPoint; Message?.Invoke(this, new AsyncTcpEventArgs("客户端连接来自 " + endpoint)); clients.TryAdd(tcpClient, true); var clientTask = Task.Run(async() => { await OnClientConnected(tcpClient); tcpClient.Dispose(); Message?.Invoke(this, new AsyncTcpEventArgs("与客户端连接 " + endpoint + "已经断开")); bool _value = false; clients.TryRemove(tcpClient, out _value); }); clientTasks.Add(clientTask); } } catch (Exception ex) { string str = ex.Message; } finally { if (closeClients) { Message?.Invoke(this, new AsyncTcpEventArgs("关闭,关闭所有客户端连接")); foreach (var tcpClient in clients.Keys) { tcpClient.Dispose(); } await Task.WhenAll(clientTasks); Message?.Invoke(this, new AsyncTcpEventArgs("已完成所有客户端连接")); } else { Message?.Invoke(this, new AsyncTcpEventArgs("关闭时,客户端连接保持打开状态")); } clientTasks.Clear(); tcpListener = null; } }