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="item">使用完的连接</param> internal void Push(SocketAsyncEventArgsWithId item) { if (item == null) { throw new ArgumentNullException("SocketAsyncEventArgsWithId对象为空"); } if (item.State == true) { if (busypool.Keys.Count != 0) { if (busypool.Keys.Contains(item.UID)) { busypool.TryRemove(item.UID, out item); } else { throw new ArgumentException("SocketAsyncEventWithId不在忙碌队列中"); } } else { throw new ArgumentException("忙碌队列为空"); } } item.UID = "-1"; item.State = false; this.pool.Push(item); }
/// <summary> /// 发送信息 /// </summary> /// <param name="uid">要发送的用户的uid</param> /// <param name="msg">消息体</param> public void Send(string uid, byte[] sendbuffer) { if (string.IsNullOrEmpty(uid) || sendbuffer.Length == 0) { return; } SocketAsyncEventArgsWithId socketWithId = readWritePool.FindByUID(uid); if (socketWithId == null) { OnSended(null, SocketError.NotSocket); return; } MySocketAsyncEventArgs e = socketWithId.SendSAEA; AsyncUserToken token = (AsyncUserToken)e.UserToken; token.FreshTime = DateTime.Now; if (e.SocketError != SocketError.Success) { OnSended(token, e.SocketError); this.CloseClientSocket(e.UID); return; } int i = 0; try { e.SetBuffer(sendbuffer, 0, sendbuffer.Length); if (!token.Socket.SendAsync(e)) { this.ProcessSend(e); } } catch (Exception) { if (i <= 5) { i++; //如果发送出现异常就延迟0.01秒再发 Thread.Sleep(10); Send(uid, sendbuffer); } else { OnSended(token, SocketError.SocketError); } } }
/// <summary> /// 服务端初始化 /// </summary> public void Init() { this.bufferManager.InitBuffer(); SocketAsyncEventArgsWithId readWriteEventArgWithId; for (Int32 i = 0; i < this.numConcurrence; i++) { readWriteEventArgWithId = new SocketAsyncEventArgsWithId(); readWriteEventArgWithId.ReceiveSAEA.Completed += new EventHandler <SocketAsyncEventArgs>(OnReceiveCompleted); readWriteEventArgWithId.SendSAEA.Completed += new EventHandler <SocketAsyncEventArgs>(OnSendCompleted); //只给接收的SocketAsyncEventArgs设置缓冲区 this.bufferManager.SetBuffer(readWriteEventArgWithId.ReceiveSAEA); this.readWritePool.Push(readWriteEventArgWithId); } serverstate = ServerState.Inited; }
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); }