예제 #1
0
    /// <summary>
    /// 接收到消息
    /// </summary>
    /// <param name="ms"></param>
    void OnReceivedMessage(int size, MemoryStream ms)
    {
        BinaryReader r = new BinaryReader(ms);

        byte[]        message = r.ReadBytes((int)(ms.Length));
        RazByteBuffer buffer  = new RazByteBuffer(message);
        int           pid     = RazConverter.GetBigEndian_Int32(buffer.ReadInt());
        int           ctxId   = RazConverter.GetBigEndian_Int32(buffer.ReadInt());

        buffer.SetSize(size);
        buffer.SetPid(pid);
        buffer.SetCtxId(ctxId);
        RazNetworkManager.AddEvent(pid, buffer);
    }
예제 #2
0
    /// <summary>
    /// 接收到消息
    /// </summary>
    void OnReceive(byte[] bytes, int length)
    {
        int IntSize = 4;

        memStream.Seek(0, SeekOrigin.End);
        memStream.Write(bytes, 0, length);
        //Reset to beginning
        memStream.Seek(0, SeekOrigin.Begin);

        while (RemainingBytes() > IntSize)
        {
            int messageLen = reader.ReadInt32();
            messageLen = RazConverter.GetBigEndian_Int32(messageLen) & 0xffffff;

            if (0 == messageLen)
            {
                memStream.Position = memStream.Position + RemainingBytes();
            }

            // Debug.LogWarning("粘包处理查看log:RemainingBytes():" + RemainingBytes() + ", messageLen:" + messageLen);

            if (messageLen > 0 && RemainingBytes() + IntSize >= messageLen)
            {
                MemoryStream ms     = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(ms);
                writer.Write(reader.ReadBytes(messageLen - IntSize));
                ms.Seek(0, SeekOrigin.Begin);
                OnReceivedMessage(messageLen, ms);
            }
            else
            {
                //Back up the position four bytes
                memStream.Position = memStream.Position - IntSize;
                break;
            }
        }
        //Create a new stream with any leftover bytes
        byte[] leftover = reader.ReadBytes((int)RemainingBytes());
        memStream.SetLength(0);     //Clear
        memStream.Write(leftover, 0, leftover.Length);
    }