private void Begin(bool init) { if (init) { if (_buffer != null && !_processingHeader) { string message = Encoding.Unicode.GetString(_buffer); Log("Received message: [" + message + "] (" + _buffer.Length + " bytes)."); if (RaiseReceivedMessage != null) { RaiseReceivedMessage.Invoke(this, message); } } _processingHeader = !_processingHeader; int len = _processingHeader ? 4 : BitConverter.ToInt32(_buffer, 0); if (len < 0) { Log("Got invalid length, synchro lost. Aborting!"); _pipeStream.Close(); return; } _buffer = new byte[len]; _cursor = 0; if (!_processingHeader && _buffer.Length == 0) { // we have NO DATA to read, notify of empty message and wait to read again. Log("Empty message."); Begin(true); return; } } try { int bufferLength = _buffer.Length - _cursor; _pipeStream.BeginRead(_buffer, _cursor, bufferLength, WhenReceived, null); Log("Waiting to read (" + bufferLength + " bytes)."); } catch (ObjectDisposedException) { Log("Nothing to read, connection closed."); } catch (IOException e) { Log("Begin Read error:" + e); } }
private void Session_RaiseReceivedMessage(object sender, string args) { //forward RaiseReceivedMessage?.Invoke(sender, args); }