private void InitClientInternal(string host, int port, TcpClientCom client) { this.connectionType = ConnectionType.Client; client.Logger = this.logger; client.ReceiveBufferSize = this.ReceiveBufferSize; client.SendBufferSize = this.SendBufferSize; client.AdjustSocketHandler = this.AdjustSocketHandler; SubscribeCommunicationEvents(client); originalTarget = new TcpTarget() { Host = host, Port = port }; client.Init(host, port); this.communication = client; if (LogDataStream) { dataStreamLogger.Init(this, host.Replace('.', '_') + "-" + port, Config != null ? Config.Root : null); } // async client connect Task.Run(StartAutoReconnectAsync); }
private void InitClient(XElement securityXml, bool isSecurityEnabled, string host, int port) { TcpClientCom client; if (isSecurityEnabled) { var secureClient = new SecureTcpClient(); secureClient.ServerName = securityXml.GetConfigParameterValue <string>(ConfigParamServerName); secureClient.ProvideClientCertificate = securityXml.GetConfigParameterValueOrDefault <bool>(false, ConfigParamProvideClientCertificate); if (secureClient.ProvideClientCertificate) { secureClient.ClientCertificateName = securityXml.GetConfigParameterValue <string>(ConfigParamClientCertificateName); } client = secureClient; } else { client = new TcpClientCom(); } InitClientInternal(host, port, client); }
protected async void StartAutoReconnectAsync() { if (Interlocked.Exchange(ref clientAutoReconnectLock, 1) == 0) // only start auto reconnect task once { try { await Task.Delay(100); if (!isActive) { if (Logger != null) { Logger.Info($"No reconnect to {communication?.EndPoint} because of shutdown"); } return; } if (this.communication.ConnectTimeUtc.HasValue) { // only if established connection is immediately reset by the remote host // sleep to prevent fast endless reconnect loop var lastConnectDiff = DateTime.UtcNow - this.communication.ConnectTimeUtc.Value; if (lastConnectDiff < ClientReconnectInterval) { await Task.Delay(ClientReconnectInterval); } } if (Logger != null) { Logger.Info($"Connect to {communication?.EndPointInfo}..."); } clientConnectCount++; string errMsg; while (!this.communication.Connect(out errMsg)) { if (Logger != null) { Logger.Warn($"Connection refused {communication?.EndPoint}! {errMsg}"); } await Task.Delay(ClientReconnectInterval); clientConnectCount++; RotateFallbackClientTargets(); } clientConnectCount = 0; } catch (Exception ex) { if (Logger != null) { Logger.Error(ex.ToString()); } await Task.Delay(1000); // pause between reconnect } finally { Interlocked.Exchange(ref clientAutoReconnectLock, 0); if (communication is TcpClientCom) { TcpClientCom client = (TcpClientCom)communication; if (!client.IsConnected && isActive) { if (ClientReconnectFailed != null) { ClientReconnectFailed(this, EventArgs.Empty); } if (logger != null) { logger.Debug("Restart reconnect processing"); } _ = Task.Run(StartAutoReconnectAsync); } } else { if (logger != null) { logger.Debug("Reconnect processing exit"); } } } } }