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 Stop() { if (CurrentStatus == ClientStatus.NotConnected) { return; } CurrentStatus = ClientStatus.Disconnecting; EventQueue.RemoveEvent(connectionTimeoutEvent); NetworkHandler.Stop(); MessageHandler.Stop(); ClientsById.Clear(); CurrentStatus = ClientStatus.NotConnected; OnDisconnected?.Invoke(); }