Ejemplo n.º 1
0
        private void ReceiveCb(IAsyncResult ar)
        {
            // 获取用户定义的数据
            Conn conn = (Conn)ar.AsyncState;

            if (conn == null || conn.socket == null || !conn.socket.Connected)
            {
                return;
            }
            lock (conn)
            {
                try
                {
                    int count = conn.socket.EndReceive(ar);
                    // 如果<=0,就是客户端关闭了
                    if (count <= 0)
                    {
                        Console.WriteLine(m_serverType + ":收到 [" + conn.GetAdress() + "] 断开链接");
                        conn.Close();
                        return;
                    }
                    conn.buffCount += count;
                    // 处理数据
                    ProcessData(conn);
                    // 继续接受,起点是缓冲区的当前位置,大小是缓冲区的剩余位置,用于分包时的接受
                    conn.socket.BeginReceive(conn.readBuff,
                                             conn.buffCount, conn.BuffRemain(),
                                             SocketFlags.None, ReceiveCb, conn);
                }
                catch (Exception e)
                {
                    Console.WriteLine(m_serverType + ":收到异常消息 [" + conn.GetAdress() + "] 断开链接:" + e);
                    conn.Close();
                }
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 发送消息是发送前压包,再发送
 /// </summary>
 private void SendMessage()
 {
     for (int i = 0; i < m_msgList.Count; i++)
     {
         MessageCache cache = m_msgList[i];
         Conn         conn  = cache.conn;
         if (conn != null && conn.socket != null && conn.socket.Connected)
         {
             NetMessage msg = cache.msg;
             m_stream.Reset();
             msg.ToByte(ref m_stream);
             try
             {
                 if (msg.msgID != 200)
                 {
                     Console.WriteLine(m_serverType + ":发送消息:" + (eNetMessageID)msg.msgID);
                 }
                 conn.socket.BeginSend(m_stream.GetBuffer(), 0, msg.msgMaxLen, SocketFlags.None, null, conn);
             }
             catch (Exception e)
             {
                 Console.WriteLine(m_serverType + ":[错误]发送消息异常,id:" + (eNetMessageID)msg.msgID + " " + conn.GetAdress() + " : " + e.Message);
             }
         }
     }
     m_msgList.Clear();
 }