private void ThreadProc() { byte[] receiveBuffer = new byte[1024]; while (!threadStopped) { while (this.stream.DataAvailable) { int bytesRead = this.stream.Read(receiveBuffer, 0, receiveBuffer.Length); var b = new byte[bytesRead]; Array.Copy(receiveBuffer, b, bytesRead); protocol.Receive(b); Send(new HeartBeat() { heartbeat = 1 }); } Thread.Sleep(1); } Send(new HeartBeat() { heartbeat = 0 }); }
public static void Test() { int iMessagesComplete = 0; var p = new MessageProtocol(); p.MessageComplete += bytes => { var messageReceived = Message.Decode(bytes); System.Diagnostics.Debug.Assert(messageReceived is TestMessage); System.Diagnostics.Debug.Assert(((TestMessage)messageReceived).Text == "Hello World!"); iMessagesComplete++; }; var m = new TestMessage() { Text = "Hello World!" }; byte[] b = m.Encode(); p.Receive(b); System.Diagnostics.Debug.Assert(iMessagesComplete == 1); byte[] firstHalf = new byte[10]; byte[] secondHalf = new byte[b.Length - firstHalf.Length]; Array.Copy(b, firstHalf, firstHalf.Length); Array.Copy(b, firstHalf.Length, secondHalf, 0, secondHalf.Length); p.Receive(firstHalf); System.Diagnostics.Debug.Assert(iMessagesComplete == 1); p.Receive(secondHalf); System.Diagnostics.Debug.Assert(iMessagesComplete == 2); byte[] twoMessages = new byte[b.Length * 2]; b.CopyTo(twoMessages, 0); b.CopyTo(twoMessages, b.Length); p.Receive(twoMessages); System.Diagnostics.Debug.Assert(iMessagesComplete == 4); }