//异步监听结束 private void EndAccept(IAsyncResult result) { Socket userToken = null; //获得客户端Socket try { userToken = socket.EndAccept(result); socket.BeginAccept(EndAccept, null); } catch { } if (userToken == null) { return; } //实例化客户端类 UserToken client = new UserToken(this, userToken); //增加事件钩子 client.SendCompleted += client_SendCompleted; client.ReceiveCompleted += client_ReceiveCompleted; client.DisconnectCompleted += client_DisconnectCompleted; //增加客户端 lock (clients) clients.Add(client); //客户端连接事件 AcceptCompleted?.Invoke(this, new SocketEventArgs(client, SocketAsyncOperation.Accept)); }
private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { UserToken userToken = m_UserTokenPool.Pop(); userToken.Socket = acceptEventArgs.AcceptSocket; acceptEventArgs.UserToken = userToken; AcceptCompleted?.Invoke(this, acceptEventArgs); //添加事件 userToken.ReceiveCompleted += client_ReceiveCompleted; userToken.SendCompleted += client_SendCompleted; userToken.DisconnectCompleted += client_DisconnectCompleted; //开始接收数据 userToken.ReceiveAsync(); //把当前异步事件释放,等待下次客户端连接 StartAccept(acceptEventArgs); }
//异步监听结束 private void EndAccept(IAsyncResult result) { Socket clientSocket = null; //获得客户端Socket try { clientSocket = socket.EndAccept(result); socket.BeginAccept(EndAccept, null); } catch { } if (clientSocket == null) { return; } //实例化客户端类 TCPListenerClient client = new TCPListenerClient(this, clientSocket); //增加客户端 lock (clients) { clients.Add(client); //客户端连接事件 AcceptCompleted?.Invoke(this, new SocketEventArgs(client, SocketAsyncOperation.Accept)); } //增加事件钩子 client.SendCompleted += client_SendCompleted; client.ReceiveCompleted += client_ReceiveCompleted; client.DisconnectCompleted += client_DisconnectCompleted; client.Start(); }