private void DisconnectClient(HostClient client) { if (clients.Count == 0) { return; } lock (clients) clients.RemoveAll(x => x.Id == client.Id); client.client?.Dispose(); client.pingTimer?.Dispose(); Log.Info($"Client {client.Id} has disconnected"); }
private async void HandleClient(HostClient clientHost, CancellationToken token) { TcpClient client = clientHost.client; clientHost.pingTimer = new Timer(Ping, client, TimeSpan.FromSeconds(0.0), TimeSpan.FromSeconds(1.0)); await Task.Run(() => { try { using (client) { using (var stream = client.GetStream()) { using (var reader = new BinaryReader(stream)) { while (client.Connected) { token.ThrowIfCancellationRequested(); if (stream.DataAvailable) { MessageType messageType = (MessageType)reader.ReadInt32(); string message = reader.ReadString(); if (messageType != MessageType.Ping) { Log.Info(messageType.ToString() + ":" + message); } MessageRecieved?.Invoke(client, messageType, message); } } } } } } catch { } finally { DisconnectClient(clientHost); } }); }
private void WaitForClients() { source?.Cancel(); source = new CancellationTokenSource(); tcpListener.Start(); Log.Info("Waiting for new clients"); while (clients.Count != 2) { var client = tcpListener.AcceptTcpClient(); var clientHost = new HostClient() { client = client, Id = clients.Count }; lock (clients) clients.Add(clientHost); HandleClient(clientHost, source.Token); Log.Info($"Client {clientHost.Id} connected"); } Log.Info("Clients are found"); tcpListener.Stop(); }