/// <summary> /// 异步连接操作完成后调用该方法 /// </summary> private void ProcessAccept(SocketAsyncEventArgs accept) { Socket s = accept.AcceptSocket; if (s != null) { try { accept.Dispose(); string sClientIP = ((IPEndPoint)s.RemoteEndPoint).ToString(); Log4Debug(sClientIP + " Client Accept"); AsyncUserToken userToken = userTokenPool.Pop(); if (userToken != null) { userToken.ConnectSocket = s; userToken.userInfo = new RoomActor(DateTime.Now); userTokenPool.AddUsed(userToken); Log4Debug("Free Client total:" + userTokenPool.Count()); SocketAsyncEventArgs e = userToken.SAEA_Receive; if (!userToken.ConnectSocket.ReceiveAsync(e)) { ProcessReceive(userToken); } } else { s.Close(); Log4Debug(sClientIP + " Can't connect server,because connection pool has been finished !"); } } catch (Exception e) { Log4Debug("ProcessAccept:" + e.Message); } } StartAccept(null); }
/// <summary> /// 当异步连接完成时调用此方法 /// </summary> /// <param name="e">操作对象</param> private void ProcessAccept(SocketAsyncEventArgs e) { // 原子操作,增加一个客户端数量 Interlocked.Increment(ref ConnectedSockets); // 从接受端重用池获取一个新的SocketAsyncEventArgs对象 AsyncUserToken userToken = TokenPool.Pop(); userToken.ServerSocket = e.AcceptSocket; // 一旦客户机连接,就准备接收。 bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(userToken.ReceiveEventArgs); if (!willRaiseEvent) { ProcessReceive(userToken.ReceiveEventArgs); } if (OnAccept != null) { OnAccept(); } // 接受第二连接的请求 StartAccept(e); }