예제 #1
0
    private void Received()
    {
        while (true)
        {
            try
            {
                // 实际接收到的有效字节数
                int len = socket.Receive(receiveBuf);
                if (len == 0)
                {
                    break;
                }
                Message msg        = null;
                int     startIndex = 0;

                UnityEngine.Debug.Log(len);
                //////////////////////// 一旦超过容量,读取buf直到为空
                bool flag = false;
                while (len == MAX_RECEIVE_SIZE)
                {
                    len  = socket.Receive(receiveBuf);
                    flag = true;
                }
                if (flag)
                {
                    continue;
                }
                //////////////////////

                // 粘包问题解决
                do
                {
                    msg = PackUtil.Unpack(receiveBuf, startIndex);
                    if (msg.id == 3)
                    {
                        lock (msgQ)
                        {
                            if (msgQ.Count == MAX_COUNT)
                            {
                                msgQ.Dequeue();
                            }
                            msgQ.Enqueue(msg);
                        }
                    }
                    else // TODO 攻击状态应该为importMsgQ
                    {
                        lock (importMsgQ)
                        {
                            importMsgQ.Enqueue(msg);
                        }
                    }
                    startIndex += (int)msg.len + 8;
                }while (startIndex < len);
            }
            catch
            {
                socket.Close();
                socket.Dispose();
                break;
            }
        }
    }