/// <summary> /// 断开与客户端的连接 /// </summary> /// <param name="client"></param> public void CloseClient(HCClient client) { try { foreach (SocketAsyncEventArgs item in m_clientPool) { if (((HCClient)item.UserToken).Equals(client)) { CloseClientSocket(item); break; } } } catch (Exception e) { ServerState?.Invoke(HCServerStateEnmu.RunningException, e.Message); } }
/// <summary> /// 关闭socket客户端 /// </summary> /// <param name="e"></param> private void CloseClientSocket(SocketAsyncEventArgs e) { try { HCClient token = e.UserToken as HCClient; if (m_clientPool.Contains(e)) { //关闭与客户端连接的socket try { token.Socket.Shutdown(SocketShutdown.Both); } catch (Exception) { //客户端已经关闭 } ClientState?.Invoke(HCClientStateEnmu.Disconnected, token); //客户端断开连接 token.Socket.Close(); token.ClearCache(); //连接数递减 Interlocked.Decrement(ref m_numConnectedSockets); //释放SocketAsyncEventArgs,以便其他客户端可以重用它们 m_readPool.Push(e); m_clientPool.Remove(e); m_maxNumberAcceptedClients.Release(); Console.WriteLine("客户端从服务器断开连接,当前服务器客户端连接数:{0}", m_numConnectedSockets); } else { Console.WriteLine("客户端从服务器断开连接"); } } catch (Exception exp) { ServerState?.Invoke(HCServerStateEnmu.RunningException, exp.Message); } }
/// <summary> /// 继续接收数据 /// </summary> /// <param name="e"></param> private void ContinueReceive(SocketAsyncEventArgs e) { try { if (e.SocketError == SocketError.Success) { HCClient token = (HCClient)e.UserToken; //读取从客户端发送的下一个数据块 bool willRaiseEvent = token.Socket.ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } } else { CloseClientSocket(e); } } catch (Exception exp) { ServerState?.Invoke(HCServerStateEnmu.RunningException, exp.Message); } }
/// <summary> /// 异步接收操作,如果远程主机关闭了连接,则关闭socket /// </summary> /// <param name="e"></param> private void ProcessReceive(SocketAsyncEventArgs e) { try { //检查远程主机是否关闭了连接 HCClient token = (HCClient)e.UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { byte[] recdata = new byte[e.BytesTransferred]; Array.Copy(e.Buffer, e.Offset, recdata, 0, recdata.Length); token.AnalysisData(recdata); ContinueReceive(e); } else {//远程主机关闭了连接 CloseClientSocket(e); } } catch (Exception exp) { ServerState?.Invoke(HCServerStateEnmu.RunningException, exp.Message); } }
/// <summary> /// 客户端运行状态 /// </summary> /// <param name="state"></param> /// <param name="client"></param> private void HCServer_ClientState(HCClientStateEnmu state, HCClient client) { }