Exemplo n.º 1
0
        void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                var state = (StateObject)ar.AsyncState;
                var s     = state.m_Socket;

                int bytesRead = s.EndReceive(ar);
                if (bytesRead > 0)
                {
                    //增加读取的索引
                    state.m_BufferReceivedSize += bytesRead;
                    //拆分包
                    TcpTools.SplitPack(ref state.m_Buffer, ref state.m_BufferReceivedSize, ref state.m_BufferSize, OnRecvPack);
                    //继续接收
                    s.BeginReceive(state.m_Buffer, state.m_BufferReceivedSize, state.m_BufferSize - state.m_BufferReceivedSize, 0, new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    Close();
                    AddEvent(TcpEventType.EventReceiveData, SocketError.NoData, "NoData");
                }
            }
            catch (SocketException e)
            {
                Close();
                AddEvent(TcpEventType.EventReceiveData, e.SocketErrorCode, e.Message);
            }
        }
Exemplo n.º 2
0
 void HandleDataReceived(IAsyncResult ar)
 {
     if (IsRunning)
     {
         var client = ar.AsyncState as Socket;
         try
         {
             int bytesRead = client.EndReceive(ar);
             if (bytesRead > 0)
             {
                 m_BufferReceivedSize += bytesRead;
                 TcpTools.SplitPack(ref m_Buffer, ref m_BufferReceivedSize, ref m_BufferSize, PushPack);
                 client.BeginReceive(m_Buffer, m_BufferReceivedSize, m_BufferSize - m_BufferReceivedSize, SocketFlags.None, new AsyncCallback(HandleDataReceived), client);
             }
             else
             {
                 Close();
             }
         }
         catch (SocketException)
         {
             Close();
         }
     }
 }