private async void StartListening() { LogOutput.Trigger("Starting to listen for input."); Listening = true; while (Listening) { try { // Based on the protocol we've defined, the first uint is the size of the message. [UInt (4)] + [Message (1*n)] - The UInt describes the length of the message. uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection). if (!Listening) { break; } if (readLength < sizeof(uint)) { Listening = false; Disconnect(); LogOutput.Trigger("The connection has been terminated."); break; } uint messageLength = reader.RReadUint(); // LogOutput.Trigger("messageLength: " + messageLength.ToString()); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(messageLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection). if (!Listening) { break; } if (readLength < messageLength) { Listening = false; Disconnect(); LogOutput.Trigger("The connection has been terminated."); break; } string message = reader.ReadString(messageLength); MessageOutput.Trigger("Received message: " + message); if (DO_RESPONSE) { SendMessage("abcdefghij"); } } catch (Exception e) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown) { Listening = false; Disconnect(); LogOutput.Trigger("Fatal unknown error occurred."); break; } } } LogOutput.Trigger("Stopped to listen for input."); }