コード例 #1
0
    //  接收数据处理
    private static void OnRecieveData()
    {
        // 消息长度
        if (readBuff.length <= 2)
        {
            return;
        }
        // 获取消息体长度
        int readIdx = readBuff.readIdx;

        byte[] bytes      = readBuff.bytes;
        Int16  bodyLength = (Int16)((bytes[readIdx + 1] << 8) | bytes[readIdx]);

        if (readBuff.length < bodyLength)
        {
            return;
        }
        readBuff.readIdx += 2;
        // 解析协议名
        int    nameCount = 0;
        string protoName = ProtoMsgBase.DecodeName(readBuff.bytes, readBuff.readIdx, out nameCount);

        if (protoName == "")
        {
            Debug.Log("OnRecieveData MsgBase.DecodeName Fail");
            return;
        }
        readBuff.readIdx += nameCount;
        // 解析协议体
        int         bodyCount = bodyLength - nameCount;
        IExtensible msgBase   = ProtoMsgBase.Decode(protoName, readBuff.bytes, readBuff.readIdx, bodyCount);

        readBuff.readIdx += bodyCount;
        readBuff.CheckAndMoveBytes();
        // 添加到消息队列
        lock (msgList) {
            msgList.Add(msgBase);
        }
        msgCount++;
        // 继续读取消息
        if (readBuff.length > 2)
        {
            OnRecieveData();
        }
    }
コード例 #2
0
    // ProtoBuf 发送数据
    public static void Send(IExtensible msg)
    {
        // 状态判断
        if (socket == null || !socket.Connected)
        {
            return;
        }

        if (isConnecting || isClosing)
        {
            return;
        }

        // 数据编码
        byte[] nameBytes = ProtoMsgBase.EncodeName(msg);
        byte[] bodyBytes = ProtoMsgBase.Encode(msg);
        int    len       = nameBytes.Length + bodyBytes.Length;

        byte[] sendBytes = new byte[2 + len];
        // 组装长度
        sendBytes[0] = (byte)(len % 256);
        sendBytes[1] = (byte)(len / 256);
        // 组装名字
        Array.Copy(nameBytes, 0, sendBytes, 2, nameBytes.Length);
        // 组装消息体
        Array.Copy(bodyBytes, 0, sendBytes, 2 + nameBytes.Length, bodyBytes.Length);
        // 写入队列
        ByteArray ba    = new ByteArray(sendBytes);
        int       count = 0;   // WriteQueue的长度

        lock (writeQueue) {
            writeQueue.Enqueue(ba);
            count = writeQueue.Count;
        }
        // send
        if (count == 1)
        {
            socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallback, socket);
        }
    }