Beispiel #1
0
        void ClientConnectCB(IAsyncResult ar)
        {
            try
            {
                Socket clientSkt = skt.EndAccept(ar);
                T      session   = new T();
                //存储会话
                sessionLst.Add(session);
                //开始监听
                session.StartRcvData(clientSkt, () =>
                {
                    if (sessionLst.Contains(session))
                    {
                        //添加移除客户端的监听
                        RemoveSessionEvent?.Invoke(session);
                        //从列表中移除
                        sessionLst.Remove(session);
                    }
                });

                //添加委托监听
                AddSessionEvent?.Invoke(session);
            }
            catch (Exception e)
            {
                NetLogger.LogMsg("客户端 异步连接错误" + e.Message, LogLevel.Error);
            }
            skt.BeginAccept(new AsyncCallback(ClientConnectCB), skt);
        }
        //异步回调
        public override void ConnectAsync(IAsyncResult ar)
        {
            try
            {
                T client = new T();
                //这里结束接收 获取刚刚连接的socket
                Socket sk = skt.EndAccept(ar);

                //开始监听  第二个是加入结束事件
                client.StartReciveData(sk,
                                       () =>
                {
                    RemoveSession(client);
                    RemoveSessionEvent?.Invoke(client);
                    SessionList.Remove(client);
                });
                //存储会话
                SessionList.Add(client);
                AddSession(client);

                //添加委托监听
                AddSessionEvent?.Invoke(client);

                //开始新一轮接收连接
                skt.BeginAccept(ConnectAsync, null);
            }
            catch (Exception e)
            {
                NetLogger.LogMsg($"服务端连接回调错误:{e}", LogLevel.Error);
                skt?.BeginAccept(ConnectAsync, null);
            }
        }
        //异步回调
        public override void ConnectAsync(IAsyncResult ar)
        {
            try
            {
                T Client = new T();
                //这里结束接收 获取刚刚连接的socket
                Socket sk = mSocket.EndAccept(ar);

                //开始监听  第二个是加入结束事件
                Client.StartReciveData(sk,
                                       () =>
                {
                    RemoveSession(Client);
                    RemoveSessionEvent?.Invoke(Client);
                    SessionList.Remove(Client);
                });
                //添加进SessionList储存
                SessionList.Add(Client);
                AddSession(Client);
                AddSessionEvent?.Invoke(Client);

                //开始新一轮接收连接
                mSocket.BeginAccept(ConnectAsync, null);
            }
            catch (Exception e)
            {
                ("ConnectAsyncError:" + e).KLog(LogLevel.Err);
                mSocket?.BeginAccept(ConnectAsync, null);
            }
        }