private async void ReadMessageFromClientAsync(TcpClient clientThatConnected) { try { NetworkStream stream = null; StreamReader reader = null; string readTextFromClient; char[] readBuffer = new char[Common.ReadBufferSize]; stream = clientThatConnected.GetStream(); reader = new StreamReader(stream, System.Text.Encoding.Unicode); while (KeepRunning) { try { int numberOfCharsReturned = await reader.ReadAsync(readBuffer, 0, readBuffer.Length); if (numberOfCharsReturned == Common.ClientDidDisconnect) { OnRaiseClientDisconnectedEvent(new CommunicationMessage(null, Common.CommunicationEventType.Disconnected)); RemoveClient(clientThatConnected); break; } readTextFromClient = new string(readBuffer).Substring(0, numberOfCharsReturned); HandleTextFromClient(CryptographyService.DecryptFromNetwork(readTextFromClient), clientThatConnected); } catch { } finally { Array.Clear(readBuffer, 0, readBuffer.Length); readTextFromClient = ""; } } } catch { OnRaiseClientDisconnectedEvent(new CommunicationMessage(null, Common.CommunicationEventType.Disconnected)); RemoveClient(clientThatConnected); } }
private async Task ReadMessageFromServerAsync(TcpClient mClient) { try { StreamReader clientStreamReader = new StreamReader(mClient.GetStream(), System.Text.Encoding.Unicode); char[] readMessageBuffer = new char[Common.ReadBufferSize]; string readTextFromServer; int readByteCount = 0; while (true) { try { readByteCount = await clientStreamReader.ReadAsync(readMessageBuffer, 0, readMessageBuffer.Length); if (readByteCount <= 0) { OnRaisePeerDisconnectedEvent(new CommunicationMessage(null, Common.CommunicationEventType.Disconnected)); mClient.Close(); break; } readTextFromServer = new string(readMessageBuffer).Substring(0, readByteCount); OnRaiseTextReceivedEvent(new CommunicationMessage(CryptographyService.DecryptFromNetwork(readTextFromServer), Common.CommunicationEventType.TextReceived)); } catch { } finally { Array.Clear(readMessageBuffer, 0, readMessageBuffer.Length); readTextFromServer = ""; } } } catch { } }