private void Receive(IAsyncResult ar) { try { _stream.EndRead(ar); var t = _bufferBytes.TrimNull(); var m = _utf.GetString(_compressed ? _compression.Inflate(t, t.Length) : t); Log.Debug("Incoming Message: {Message}", m); ProtocolParser.Parse(m); // Clear the buffer otherwise we get leftover tags and it confuses the parser. _bufferBytes.Clear(); if (!Connected || ProtocolState.State is DisconnectedState) { return; } _stream.BeginRead(_bufferBytes, 0, _bufferBytes.Length, Receive, null); } catch (SocketException e) { Log.Error(e, "Error in socket receiving data."); } catch (InvalidOperationException e) { Log.Error(e, "Socket committed an invalid operation trying to receive data."); } }
private void OnSocketReaderCompleted(IAsyncOperationWithProgress <IBuffer, uint> asyncInfo, AsyncStatus asyncStatus) { if (asyncStatus == AsyncStatus.Completed) { _manager.ProcessComplete.Reset(); IBuffer readBuffer = asyncInfo.GetResults(); if (readBuffer.Length == 0) { // This is not neccessarily an error, it can be just fine //ConnectionError(ErrorType.ServerDisconnected, "Server sent empty package"); return; } // Get data byte[] readBytes = new byte[readBuffer.Length]; DataReader dataReader = DataReader.FromBuffer(readBuffer); dataReader.ReadBytes(readBytes); dataReader.DetachBuffer(); // Check if it is a keepalive if (!(readBytes.Length == 1 && (readBytes[0] == 0 || readBytes[0] == ' '))) { // Trim readBytes = readBytes.TrimNull(); if (readBytes == null || readBytes.Length == 0) { ConnectionError(ErrorType.ServerDisconnected, ErrorPolicyType.Reconnect, "Server sent empty package"); return; } // Decompress if (_isCompressionEnabled) { readBytes = _compression.Inflate(readBytes, readBytes.Length); } // Encode to string string data = _encoding.GetString(readBytes, 0, readBytes.Length); // Add to parser #if DEBUG _manager.Events.LogMessage(this, LogType.Debug, "Incoming data: {0}", data); #endif _manager.Parser.Parse(data); } _manager.ProcessComplete.Set(); SocketRead(); } else if (asyncStatus == AsyncStatus.Error) { ConnectionError(ErrorType.SocketReadInterrupted, ErrorPolicyType.Reconnect); return; } }
private void Receive(IAsyncResult ar) { try { _stream.EndRead(ar); var t = _buff.TrimNull(); var m = _utf.GetString(_compressed ? _comp.Inflate(t, t.Length) : t); Logger.DebugFormat(this, "Incoming Message: {0}", m); ProtocolParser.Parse(m); // Clear the buffer otherwise we get leftover tags and it confuses the parser. _buff.Clear(); if (!Connected || ProtocolState.State is DisconnectedState) { return; } _stream.BeginRead(_buff, 0, _buff.Length, Receive, null); } catch (SocketException e) { Logger.DebugFormat(this, "Socket Exception: {0}", e); } catch (InvalidOperationException e) { Logger.DebugFormat(this, "Invalid Operation: {0}", e); } }