public void SendMessage(DebugMessage msg) { if (m_writer != null) { using (MemoryStream s = new MemoryStream()) { BinaryWriter writer = new BinaryWriter(s); msg.Serialize(writer); int length = (int)s.Length; m_writer.Write(msg.Identifier); m_writer.Write(length); } // Write it again, but now write it to the network stream msg.Serialize(m_writer); } }
private void NetworkMessageThread() { // Update the state: while (!m_exitNetworkThread) { // Read messages until the connection runs out of data while (m_client.Available > 8) { // Read the network message: try { uint type = m_reader.ReadUInt32(); int size = m_reader.ReadInt32(); List <byte> bytesRead = new List <byte>(); while (bytesRead.Count < size) { if (m_client.Available > 0) { byte[] readbytes = m_reader.ReadBytes(Math.Min(m_client.Available, size - bytesRead.Count)); bytesRead.AddRange(readbytes); } else { Thread.Sleep(0); // go asleep for a bit, waiting for the data to come in. } } byte[] bytes = bytesRead.ToArray(); DebugMessage msg = DebugMessageFactory.CreateDebugMessage(type); // If we can't create this message yet, discard it if (msg != null) { using (Stream s = new MemoryStream(bytes)) { BinaryReader reader; if (m_bigEndian) { reader = new BinaryReaderEndianSwap(s); } else { reader = new BinaryReader(s); } msg.Deserialize(reader); } // Add the network message to the queue of messages: lock ( m_thisLock ) { m_networkMessages.Enqueue(msg); } } } catch { // On any error, we disconnect: Disconnect(); } } // Go to sleep for a bit: Thread.Sleep(10); } }