Exemplo n.º 1
0
    private void ReceiveData()
    {
        if (socket == null || !socket.Connected)
        {
            Close();
            return;
        }
        else
        {
            recvStream.Clear();
            int i = socket.Receive(recvStream.buf);

            if (i < 0)
            {
                Close();
                return;
            }

            recvStream.used = i;
            recvBuf.Append(recvStream);
            //当缓存中剩余未读数据至少是2字节时继续读(2字节为包长度大小)
            while (recvBuf.UnreadBytes > 2 && socket != null)
            {
                int msgLen = recvBuf.ReadInt16();

                //如果剩余未读是完整数据包则读取 否则接收到完整数据包再读
                if (msgLen > recvBuf.UnreadBytes)
                {
                    int           cmd = recvBuf.ReadInt16();
                    ReceivePacket p   = messagePacker.Read(cmd, recvBuf, msgLen - 2);//减去cmd的2位
                    if (p != null)
                    {
                        packetPool.AddReceivePacket(p);
                    }

                    if (recvBuf.UnreadBytes == 0)
                    {
                        recvBuf.Clear();
                        return;
                    }
                }
                else
                {
                    recvBuf.readPos -= 2;
                    return;
                }
            }
        }
    }