Пример #1
0
        //Accept回调
        private void AcceptCb(IAsyncResult asyncResult)
        {
            try
            {
                Socket socket = listenfd.EndAccept(asyncResult);
                int    index  = NewIndex();
                if (index < 0)
                {
                    socket.Close();
                    Console.Write("[警告]连接已满");
                }
                else
                {
                    Conn conn = conns[index];
                    conn.Init(socket);
                    string adr = conn.GetAddress();
                    Console.WriteLine("客户端连接[" + adr + "]  conn池ID:" + index);

                    //异步接收客户端数据
                    conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn);
                }

                //再次调用 BeginAccept实现循环
                listenfd.BeginAccept(AcceptCb, null);
            }
            catch (Exception e)
            {
                Console.WriteLine("AcceptCb失败:" + e.Message);
            }
        }
Пример #2
0
        private void ReceiveCb(IAsyncResult asyncResult)
        {
            Conn conn = (Conn)asyncResult.AsyncState;

            lock (conn)
            {
                try
                {
                    //获取接收的字节数
                    int count = conn.socket.EndReceive(asyncResult);
                    //Console.WriteLine("");
                    //Console.WriteLine("[ServNet] 接收到字节数 count = " + count+"-------------------------------------------------------");
                    //关闭信号
                    if (count <= 0)
                    {
                        Console.WriteLine("[ServNet] 收到 " + conn.GetAddress() + " 断开连接");
                        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("[ServNet] 收到 " + conn.GetAddress() + " 断开连接-异常触发  " + e.Message);
                    conn.Close();
                }
            }
        }