protected void ConnectToServer(Boolean isReconnect) { if (!isReconnect) { LogManager.LogStatus("{0} starting", name); } if (tcpClientSocket != null) { if (tcpClientSocket.Connected) { return; } try { tcpClientSocket.Close(); } catch (Exception) { } finally { tcpClientSocket = null; } } if (isReconnect && AutoReconnectWhenConnectionIsLost) { LogManager.LogStatus("Connection lost to server {0}. Reconnecting", RemoteIPEndPoint.ToString()); } if ((!isReconnect || (isReconnect && AutoReconnectWhenConnectionIsLost)) && listenerState != ListenerStates.Stopped && listenerState != ListenerStates.Stopping) { listenerState = ListenerStates.Connecting; tcpClientSocket = new Socket(LocalIPEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tcpClientSocket.Blocking = false; tcpClientSocket.BeginConnect(RemoteIPEndPoint, new AsyncCallback(OnConnectedToServer), tcpClientSocket); } }
protected void OnConnectedToServer(IAsyncResult asyncResult) { if (tcpClientSocket == null) { return; } try { tcpClientSocket.EndConnect(asyncResult); LogManager.LogStatus("{0} connected to {1}{2} ", name, address, (port == null ? String.Empty : ":" + port.Value.ToString())); if (tcpClientSocket.Connected) { listenerState = ListenerStates.Running; if (listenerState == ListenerStates.Running) { OnConnectedToServer(tcpClientSocket); } } else { ConnectToServer(true); } } catch (SocketException se) { if (se.SocketErrorCode == SocketError.TimedOut && (listenerState != ListenerStates.Stopping || listenerState != ListenerStates.Stopped)) { int retryInterval = ConfigurationAppSettingsWrapper <int> .GetValue("Tcp Connection retry interval"); LogManager.LogError("Timed out connecting to {0}. Retrying", RemoteIPEndPoint.ToString()); connectWaitEvent.Reset(); connectWaitEvent.WaitOne(new TimeSpan(0, 0, 0, 0, retryInterval)); try { if (tcpClientSocket != null) { tcpClientSocket.BeginConnect(RemoteIPEndPoint, new AsyncCallback(OnConnectedToServer), tcpClientSocket); } } catch (Exception) { if (listenerState != ListenerStates.Stopping || listenerState != ListenerStates.Stopped) { throw; } } } else if (se.SocketErrorCode == SocketError.ConnectionRefused && (listenerState != ListenerStates.Stopping || listenerState != ListenerStates.Stopped)) { int retryInterval = ConfigurationAppSettingsWrapper <int> .GetValue("Tcp Connection retry interval"); LogManager.LogError("Unable to connect to {0}. Retrying", RemoteIPEndPoint.ToString()); connectWaitEvent.Reset(); connectWaitEvent.WaitOne(new TimeSpan(0, 0, 0, 0, retryInterval)); try { if (tcpClientSocket != null) { tcpClientSocket.BeginConnect(RemoteIPEndPoint, new AsyncCallback(OnConnectedToServer), tcpClientSocket); } } catch (Exception) { if (listenerState != ListenerStates.Stopping || listenerState != ListenerStates.Stopped) { throw; } } } else { LogManager.LogError(se); } } }
/// <summary> /// 处理连接 /// </summary> /// <param name="ct">信号量</param> public void ProcessConnect(System.Threading.CancellationToken ct) { int count = 60; Logger.Debug("定时处理客户端连接服务开始运行"); while (IsProcessRun) { try { if (ct.IsCancellationRequested) { break; } if (!easyClient.IsConnected) { Logger.Debug($"客户端状态不正常: {easyClient.IsConnected} 即将重启启动 服务地址:【{RemoteIPEndPoint.ToString()}】"); AckMessageQueue.Clear(); var t = easyClient.ConnectAsync(RemoteIPEndPoint); Task.WaitAll(t); if (t.Result) { string str = Newtonsoft.Json.JsonConvert.SerializeObject(TopicMode); System.Threading.Interlocked.Increment(ref _instanceNumber); AckMessageQueue.Enqueue(Common.MQTools.GetMQDataInfoMessage((byte)Common.CommanCode.CreateTopic, str, _instanceNumber, mqType: 1)); Logger.Info($"客户端重新启动:【成功】添加主题消息队列【{AckMessageQueue.Count}】,编号:【{_instanceNumber}】内容:【{str}】"); count = 60; continue; } Logger.Debug($"客户端状态不正常:【重启失败】 服务地址:【{RemoteIPEndPoint.ToString()}】"); } else if (count == 60) { if (ct.IsCancellationRequested) { break; } AckFlag = true; //Logger.Debug("开始定时处理客户端确认消息队列"); //if (AckMessageQueue.Count > 0) //{ // var model = AckMessageQueue.Peek(); // Logger.Info($"定时处理:【{easyClient.LocalEndPoint}】确认消息:【{model.ToString()}】"); // easyClient.Send(Common.MQTools.GetSendMessageByte(model)); //} //Logger.Debug("结束定时处理客户端确认消息队列"); } count--; if (count % 20 == 0 && easyClient.IsConnected)//心跳 { Logger.Debug($"客户端:【{easyClient.LocalEndPoint}】开始推送心跳消息"); easyClient.Send(Common.MQTools.GetSendMessage((byte)Common.CommanCode.Heartbeat, "", 0)); Logger.Debug("结束推送心跳消息"); } if (count <= 0) { count = 60; } } catch (Exception e) { Logger.Error("处理确认消息失败", e); } if (ct.IsCancellationRequested) { break; } System.Threading.Thread.Sleep(this.Interval); } Logger.Debug("定时处理客户端连接服务结束运行"); }