public async Task <NetworkStream> AcceptRelayedStreamAsync() { NetworkStream stream = _control.GetStream(); while (true) { _connectAttempted = new TaskCompletionSource <ConnectionAttempt>(); ConnectionAttempt attempt = await _connectAttempted.Task; byte[] id = attempt.ConnectionId; var relayedClient = new TcpClient(_host, _port); NetworkStream relayedStream = relayedClient.GetStream(); var bindRequest = new ConnectionBindRequest(id); await SendMessageAsync(relayedStream, bindRequest); StunMessage bindResponse = await StunMessage.Parse(relayedStream); if (bindResponse is ConnectionBindSuccessResponse) { _relayedClients.Add(relayedClient); return(relayedStream); } throw new TurnClientException( "ConnectionBind failed.", bindResponse); } }
public async Task <NetworkStream> AcceptRelayedStreamAsync( CancellationToken cancellationToken = default(CancellationToken)) { while (true) { EnsureConnection(); ConnectionAttempt attempt = await _connectionAttempts.DequeueAsync(cancellationToken); byte[] id = attempt.ConnectionId; var bindRequest = new ConnectionBindRequest(id); var relayedClient = new TcpClient(_host, _port); NetworkStream relayedStream = relayedClient.GetStream(); try { await SendMessageAsync(relayedStream, bindRequest, cancellationToken); StunMessage bindResponse = await StunMessage.Parse(relayedStream); if (bindResponse is ConnectionBindSuccessResponse) { _relayedClients.Add(relayedClient); return(relayedStream); } throw new TurnClientException("ConnectionBind failed.", bindResponse); } catch (IOException e) { Log.Warning(e, "The connection seems to disconnect before parsing; ignored."); } } }
public void Report(ConnectionAttempt attempt) { if (!Config.HasTripLinks) { return; } Attempts.AddOrUpdate(attempt.IP, (ip) => { var newDict = new ConcurrentDictionary <int, ConcurrentBag <DateTimeOffset> >(); newDict.TryAdd(attempt.Port, new ConcurrentBag <DateTimeOffset>() { attempt.Time }); return(newDict); }, (ip, innerDict) => { innerDict.AddOrUpdate(attempt.Port, (port) => { return(new ConcurrentBag <DateTimeOffset>() { attempt.Time }); }, (port, bag) => { bag.Add(attempt.Time); return(bag); }); return(innerDict); }); }
protected override async void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) { Logger.LogTrace("Opening new UDP connection..."); try { var remote = endpoint as IPEndPoint; var attempt = new ConnectionAttempt(remote.Address, DateTime.UtcNow, Port); Reporter.Report(attempt); Logger.LogInformation($"Catched {remote.Address}"); if (Config.EnableOutput) { await File.AppendAllTextAsync(Config.OutputPath, JsonConvert.SerializeObject(attempt) + "\r\n"); } await Protocol.PerformHandshakeAsync(endpoint); } catch (Exception ex) { Logger.LogError(ex, "An error occured while someone connected to the UDP Server!"); } }
public void ConstructedObjectHasExpectedState() { var t = DateTimeOffset.Now; var o = new ConnectionAttempt(t); o.Time.Should().Be(t); o.FailedStates.Should().NotBeNull(); o.FailedStates.Should().BeEmpty(); }
private void Initialize() { _callbacks = new Dictionary <string, Action <ReceivedMessage> >(); _updateCallbacks = new Dictionary <string, Action <ReceivedMessage> >(); _updateCallbackQueue = new Queue <ReceivedMessage>(); _serializer = new MsgPackCliSerializer(); _simplSocketClient.MessageReceived += MessageReceived; _simplSocketClient.Connected += (s, e) => { Connected?.Invoke(s, e); }; _simplSocketClient.Disconnected += (s, e) => { Disconnected?.Invoke(s, e); }; _simplSocketClient.ConnectionAttempt += (s, e) => { ConnectionAttempt?.Invoke(s, e); }; }
public static void JoinRoom(string password) { ConnectionIsEstablished = false; ConnectionAttempt = GameObject.FindObjectOfType <NetworkConnectionAttemptHandler>(); Uri uri = new Uri(Network.ServerUri); NetworkManager.singleton.StartClient(uri); ConnectionAttempt.StartAttempt(); }
private async Task KeepConnectedAsync(IPEndPoint endPoint) { while (_connectionMode == ConnectionModes.fixedEndPoint) { if (!_isConnected) { ConnectionAttempt?.Invoke(this, new ServerEndpointArgs(endPoint)); SafeConnect(endPoint); await Task.Delay(1000); } } }
public void FailedStatesAccumulatesAndPreservesOrder() { var first = new AttemptFailedState(ConnectionState.Failed, ErrorInfo.ReasonClosed); var second = new AttemptFailedState(ConnectionState.Connecting, ErrorInfo.ReasonTimeout); var third = new AttemptFailedState(ConnectionState.Closed, ErrorInfo.ReasonUnknown); var o = new ConnectionAttempt(DateTimeOffset.Now); o.FailedStates.Add(first); o.FailedStates.Add(second); o.FailedStates.Add(third); o.FailedStates.Count.Should().Be(3); o.FailedStates[0].Should().Be(first); o.FailedStates[1].Should().Be(second); o.FailedStates[2].Should().Be(third); }
private async Task KeepConnectedAsync(string serverName) { var ipaddresses = NetworkHelper.GetCurrentIpv4Addresses(); while (_connectionMode == ConnectionModes.Discovery) { // Check if not connected if (!_isConnected) { lock (_beaconsLock) { // if (_beacons != null) { foreach (var beacon in _beacons) { ConnectionAttempt?.Invoke(this, new ServerEndpointArgs(beacon.Address)); if (SafeConnect(beacon.Address)) { break; } // Check if IP adress received is a local adress if (ipaddresses.Contains(beacon.Address.Address)) { var loopBackEndPoint = new IPEndPoint(IPAddress.Loopback, beacon.Address.Port); ConnectionAttempt?.Invoke(this, new ServerEndpointArgs(loopBackEndPoint)); if (SafeConnect(loopBackEndPoint)) { break; } } } } } } await Task.Delay(1000); } }
protected override async void OnConnected(TcpSession session) { Logger.LogTrace("Opening new TCP connection..."); try { var remote = session.Socket.RemoteEndPoint as IPEndPoint; var attempt = new ConnectionAttempt(remote.Address, DateTime.UtcNow, Port); Reporter.Report(attempt); Logger.LogInformation($"Catched {remote.Address}"); if (Config.EnableOutput) { await File.AppendAllTextAsync(Config.OutputPath, JsonConvert.SerializeObject(attempt) + "\r\n"); } } catch (Exception ex) { Logger.LogError(ex, "An error occured while someone connected to the TCP Server!"); } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ConnectionAttempt obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
public override async Task Connect(ConnectionAttempt request, IServerStreamWriter <PrivateEvent> responseStream, ServerCallContext context) { if (string.IsNullOrEmpty(request.Secret) || string.IsNullOrEmpty(request.AppId)) { await responseStream.WriteAsync(login_failure); return; } var login_result_nullable = instance_servers.AddServer(new InstanceServerLogin { app_id = request.AppId, secret = request.Secret }, responseStream, context); if (!login_result_nullable.HasValue) { await responseStream.WriteAsync(login_failure); return; } var login_result = login_result_nullable.Value; if (!await player_store.AddServer(login_result.guid)) { instance_servers.RemoveServer(login_result.guid); await responseStream.WriteAsync(login_failure); return; } try { await responseStream.WriteAsync(new PrivateEvent { LoginResult = new LoginResult { Success = true, Token = login_result.guid.ToString() } }); for (; ;) { if (!await login_result.stream.SendCurrentEvents()) { break; } await Task.Delay(100); } } catch (InvalidOperationException) { //Happens when cancellation token is set to true } catch (RpcException) { //Expected to happen if main server goes down. } catch (Exception e) { Log.Exception(e); } finally { login_result.stream.Nullify(); Debug.Assert(instance_servers.RemoveServer(login_result.guid)); var players_on_server = await player_store.RemoveServer(login_result.guid); if (players_on_server != null) { foreach (var player in players_on_server) { var player_permanent_id = player.Key; var stream = player.Value.player_stream; stream.Enqueue(server_dc); } } } }