public void NetworkLoop() { while (running) { int disconnectClient = 0; bool activity = false; foreach (KeyValuePair <int, TcpClient> kvp in clients) { int clientID = kvp.Key; TcpClient readClient = kvp.Value; if (readClient.Connected && readClient.Available > 0) { activity = true; try { int readBytes = readClient.GetStream().Read(readBuffer, 0, readBuffer.Length); networkHandler.HandleTCPMessage(clientID, readBuffer, readBytes); } catch (Exception e) { Console.WriteLine("Error during TCP read: " + e.Message); disconnectClient = clientID; } } if (readClient.Connected) { byte[] sendMessage = networkHandler.GetTCPMessage(clientID); if (sendMessage != null) { activity = true; try { readClient.GetStream().Write(sendMessage, 0, sendMessage.Length); } catch (Exception e) { Console.WriteLine("Error during TCP write: " + e.Message); disconnectClient = clientID; } } } if (networkHandler.ShouldDisconnect(clientID)) { Console.WriteLine("UDP Timeout for connection " + clientID); disconnectClient = clientID; } } if (disconnectClient != 0) { DisconnectClient(disconnectClient); } if (!activity) { Thread.Sleep(10); } } }