示例#1
0
 private void SendMessage()
 {
     while (true)
     {
         if (!m_isConnected)
         {
             Debug.LogWarning("SendMessage lost connection");
             break;
         }
         lock (m_lock)
         {
             if (m_sendQueue.Count > 0)
             {
                 Message msg = m_sendQueue.Dequeue();
                 m_socket.Send(msg.ToArray());
             }
         }
     }
 }
示例#2
0
        private void ReadMessage(List <byte> list)
        {
            // 读取数据长度
            if (list.Count < 4)
            {
                return;
            }

            byte[] sizeData = list.GetRange(0, 4).ToArray();
            int    size     = 0;

            using (MemoryStream stream = new MemoryStream(sizeData))
            {
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    size = reader.ReadInt32();
                }
            }

            if (list.Count < 4 + size)
            {
                return;
            }

            // 读取数据
            byte[] buffer = list.GetRange(4, size).ToArray();
            list.RemoveRange(0, 4 + size);

            using (MemoryStream stream = new MemoryStream(buffer))
            {
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    int    msgID    = reader.ReadInt32();
                    byte[] data     = reader.ReadBytes(size - 8);
                    uint   checksum = reader.ReadUInt32();

                    Message msg = new Message();
                    msg.Size      = size;
                    msg.MessageID = msgID;
                    msg.Data      = data;
                    msg.Checksum  = checksum;

                    if (msg.Verify())
                    {
                        // 心跳包
                        if (msg.MessageID == 0)
                        {
                            Message hb = new Message(0, new byte[] { });
                            // PushMessage(hb); // 删除这句,直接在线程中发送消息
                            m_socket.Send(hb.ToArray()); // 直接在线程中发送消息,这样后台运行也没关系
                        }
                        else
                        {
                            this.onMessage(msg);
                        }
                    }
                }
            }

            // 递归
            ReadMessage(list);
        }