private void ConnectAsync() { try { tcpClient.BeginConnect(configInfo.RemoteIPAddress, configInfo.RemotePort, ar => { var tcpClient = ar.AsyncState as TcpClient; try { tcpClient.EndConnect(ar); KeepAliveHelper.SetKeepAlive(tcpClient.Client, 1000, 1000); } catch (Exception e) { loggerFactory?.GetLogger(Name).Error(e.ToString()); } }, tcpClient); } catch (Exception e) { loggerFactory?.GetLogger(Name).Error(e.ToString()); } }
private void AcceptTcpClientAsync() { try { tcpListener.BeginAcceptTcpClient(ar => { var tcpListener = ar.AsyncState as TcpListener; try { TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar); var ipAddress = string.Empty; tcpClient.ReceiveTimeout = configInfo.ReceiveTimeout; tcpClient.SendTimeout = configInfo.SendTimeout; KeepAliveHelper.SetKeepAlive(tcpClient.Client, 1000, 1000); ipAddress = tcpClient.Client.RemoteEndPoint.ToString().Split(':').First(); if (!tcpClientInfoDictionary.ContainsKey(ipAddress)) { var tcpClientInfo = new TcpClientInfo() { IPAddress = ipAddress, ComPort = new TcpClientWapper(tcpClient, loggerFactory) }; tcpClientInfoDictionary.Add(ipAddress, tcpClientInfo); } (tcpClientInfoDictionary[ipAddress].ComPort as TcpClientWapper).TcpClient = tcpClient; OnTcpClientAccepted(this, new TcpClientAcceptedEventArgs() { TcpClientInfo = tcpClientInfoDictionary[ipAddress] }); if (type == TcpListenerComPortType.One2One) { connectionStateChangedEventManager.StartMonitor(ConnectionStateChanged, this, tcpClient); } } catch (Exception e) { loggerFactory?.GetLogger(Name).Error(e.ToString()); } AcceptTcpClientAsync(); }, tcpListener); } catch (Exception e) { loggerFactory?.GetLogger(Name).Error(e.ToString()); } }
private void ConnectSync() { try { tcpClient.Connect(configInfo.RemoteIPAddress, configInfo.RemotePort); KeepAliveHelper.SetKeepAlive(tcpClient.Client, 1000, 1000); } catch (Exception e) { var ex = new ApplicationException("打开通讯端口失败", e); loggerFactory?.GetLogger(Name).Error(ex.ToString()); throw ex; } }