public void CloseClientSocket(string uid) { if (string.IsNullOrEmpty(uid)) { return; } SocketAsyncEventArgsWithId saeaw = readWritePool.FindByUID(uid); if (saeaw == null) { return; } //先将连接从活跃池中取出,再进行断开,因为断开会触发接收消息 this.readWritePool.Push(saeaw); AsyncUserToken token = saeaw.ReceiveSAEA.UserToken as AsyncUserToken; token.Socket.Shutdown(SocketShutdown.Both); this.semaphoreAcceptedClients.Release(); Interlocked.Decrement(ref this.numConnections); OnClientNumberChange?.Invoke(-1, token); }
/// <summary> /// 构造函数 /// </summary> /// <param name="numConnections">最大连接数</param> /// <param name="receiveBufferSize">缓存区大小</param> public SocketManager(int numConnections, int receiveBufferSize) { m_clientCount = 0; m_maxConnectNum = numConnections; m_revBufferSize = receiveBufferSize; // allocate buffers such that the maximum number of sockets can have one outstanding read and //write posted to the socket simultaneously m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToAlloc, receiveBufferSize); m_pool = new SocketEventPool(numConnections); m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections); ClientNumberChange = new OnClientNumberChange(ShowClient); ReceiveClientData = new OnReceiveData(GetMsg); }
private void ProcessAccept(SocketAsyncEventArgs e) { if (GetIDByEndPoint == null) { throw new ArgumentException("The function GetIDByEndPoint can not be null!"); } if (e.LastOperation != SocketAsyncOperation.Accept) //检查上一次操作是否是Accept,不是就返回 { return; } string UID = GetIDByEndPoint(e.AcceptSocket.RemoteEndPoint as IPEndPoint); //根据IP获取用户的UID if (string.IsNullOrEmpty(UID)) { return; } if (readWritePool.BusyPoolContains(UID)) //判断现在的用户是否已经连接,避免同一用户开两个连接 { return; } SocketAsyncEventArgsWithId readEventArgsWithId = this.readWritePool.Pop(UID); AsyncUserToken userToken = new AsyncUserToken { UID = UID, Socket = e.AcceptSocket, ConnectTime = DateTime.Now, FreshTime = DateTime.Now, Remote = e.AcceptSocket.RemoteEndPoint as IPEndPoint }; readEventArgsWithId.ReceiveSAEA.UserToken = userToken; readEventArgsWithId.SendSAEA.UserToken = userToken; //激活接收 if (!e.AcceptSocket.ReceiveAsync(readEventArgsWithId.ReceiveSAEA)) { ProcessReceive(readEventArgsWithId.ReceiveSAEA); } Interlocked.Increment(ref this.numConnections); OnClientNumberChange?.Invoke(1, userToken); this.StartAccept(e); }