private void OnDataReceived(object sender, DataReceivedEventArgs e) { var client = sender as Client; // Check the buffer stream after decoding. if (_overflowBuffer.Length + e.Data.Length > MaxMessageSize) { // We will not even bother to decode the next bytes since we assume it's garbage. client?.Disconnect("MaxMessageSize reached."); return; } // Decode the message bytes. var decoded = _encoder.Decode(e.Data); // Parse to string var receivedBuffer = StringEncoding.GetString(decoded); var messageBuffer = _overflowBuffer + receivedBuffer; // NOTE: Normally you should disconnect people who send 'empty' packets but the developers messed up some where so the client might send \n\n twice. // This does not apply to all client versions so make sure you check your version. var messages = messageBuffer.Split(MessageDelimiter, StringSplitOptions.RemoveEmptyEntries); foreach (var message in messages) { // Parse message. var parseMessage = message.Trim(); try { var wrMessage = MessageProcessor.Parse(parseMessage) as BaseMessage; if (wrMessage != null) { MessageReceived.Invoke(this, new WrMessageReceivedEventArgs(wrMessage)); } else { Console.WriteLine("Failed to parse message: {0}", parseMessage); } } catch (Exception exception) { Console.WriteLine("Parse Exception: {0}", exception); } } _overflowBuffer = string.Empty; if (!messageBuffer.EndsWith("\n")) { // The last message is split, remember this for the next receive call. _overflowBuffer = messages[messages.Length - 1]; } }
private byte[] ParseAndDecode(BinaryReader reader, int count) { var encodedBuffer = reader.ReadBytes(count); return(_codec.Decode(encodedBuffer)); }