Exemplo n.º 1
0
        void ReceiveThread()
        {
            IoBuffer temBuffer = new IoBuffer(ONCE_SIZE * 2);

            while (m_isIOThreadActive)
            {
                //如果空间不够
                if (temBuffer.WriteRemain < ONCE_SIZE)
                {
                    //如果移到太靠后的位置了,那么整体挪到开始的位置
                    if (temBuffer.ReadPos > ONCE_SIZE * 3)
                    {
                        temBuffer.MoveToFirst();
                    }
                    //否则再申请点
                    else
                    {
                        temBuffer.EnsureCapacity(ONCE_SIZE);
                    }
                }

                try
                {
                    SocketError error  = SocketError.Success;
                    int         length = m_socket.Receive(temBuffer.Buffer, temBuffer.WritePos, ONCE_SIZE, SocketFlags.None, out error);
                    if (error != SocketError.Success)//接收不成功的话可能因为延迟很高,暂时的处理是掉线,经常出现的话可以考虑改为重新接收
                    {
                        AddError(error, "m_socket.Receive error");
                        return;
                    }
                    if (length == 0)
                    {
                        AddError(error, "Socket shutdown gracefully");
                        return;
                    }
                    temBuffer.WritePos += length;

                    //解码
                    decode(temBuffer, m_recvMessageList);
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    AddError(e.SocketErrorCode, e.Message + "\n" + e.StackTrace);//告诉主线程,然后主线程会传给上层
                    return;
                }
                catch (Exception e)
                {
                    AddError(SocketError.SocketError, e.Message + "\n" + e.StackTrace);//告诉主线程,然后主线程会传给上层
                    return;
                }

                //如果完全读取完成了重置下
                if (temBuffer.ReadSize == 0)
                {
                    temBuffer.Reset();
                }
            }
        }