public async Task ConnectManyAsync(IEndPoint[] endPoints, IEndPoint sourceEndPoint, bool invokeEvents, IAsymmetricKey key, ISymmetricKey dummySymmetricKey, byte[] selfCustomData) { if (CurrentStatus != ClientStatus.NotConnected) { return; } if (selfCustomData.Length > 65000) { throw new DnmpException("Custom data length is larger than 65000 bytes"); } SelfCustomData = selfCustomData; Initialize(sourceEndPoint, key, dummySymmetricKey); CurrentStatus = ClientStatus.Connecting; if (invokeEvents) { connectionTimeoutEvent = EventQueue.AddEvent(_ => { NetworkHandler.Stop(); MessageHandler.Stop(); ClientsById.Clear(); CurrentStatus = ClientStatus.NotConnected; OnConnectionTimeout?.Invoke(); }, null, DateTime.Now.AddMilliseconds(Config.ConnectionTimeout)); } else { connectionTimeoutEvent = EventQueue.AddEvent(_ => { CurrentStatus = ClientStatus.NotConnected; }, null, DateTime.Now.AddMilliseconds(Config.ConnectionTimeout)); } logger.Debug($"Trying to connect to {endPoints.Length} endpoints. First: {endPoints.FirstOrDefault()}"); foreach (var endPoint in endPoints) { logger.Debug($"Trying to connect to {endPoint}"); try { NetworkHandler.SendBaseMessage( new BaseMessage(new ConnectionRequestMessage(key.GetNetworkId(), true), 0xFFFF, 0xFFFF), endPoint); } catch (Exception e) { logger.Warn($"Caught exception while trying to connect: {e.GetType().Name}('{e.Message}')"); } } if (invokeEvents) { return; } SpinWait.SpinUntil(() => CurrentStatus == ClientStatus.Connecting || CurrentStatus == ClientStatus.Handshaking); if (CurrentStatus == ClientStatus.NotConnected) { throw new TimeoutException("Connection timeout"); } await Task.Delay(0); }
public void UpdateTimeout(float deltaTime) { timeout += deltaTime; if (autoPing) { pingBuffer += deltaTime; if (pingBuffer >= pingInterval) { pingBuffer -= pingInterval; Write(new Ping()); } } if (timeout >= timeoutThreshold) { onConnectionTimeout?.Invoke(this); } }
/// <summary> /// 每秒一次定期检查,用于清零计数器,检查远端可用性,检查闲置时间,发送闲置数据包 /// </summary> private void ScheduleCheck(ThreadPoolTimer Timer) { //检查发送计数器,发送闲置包 if (UploadCount == 0) { ; } //清零计数器,唤醒线程 UploadCount = 0; Wait.Set(); //检查闲置时间,生成超时事件 if (IdleTime.Elapsed > DefaultSettings.Value.MaxmumIdleTime) { OnConnectionTimeout?.Invoke(this, new ConnectionTimeoutEventArgs(Client.Information.RemoteHostName.CanonicalName, Client.Information.RemotePort, Client.Information.LocalPort)); //传说中又臭又长的代码 } //增加计数器 TotalRunningTime++; }