/// <summary> /// 此方法在异步发送操作完成时调用。 /// 该方法在套接字上发出另一个receive,以读取从客户端发送的任何附加数据 /// </summary> /// <param name="e"></param> private void ProcessSend(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { // 已将数据回显到客户端 AsyncUserToken token = (AsyncUserToken)e.UserToken; // 读取从客户端发送的下一个数据块 bool willRaiseEvent = token.Socket.ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } } else { CloseClientSocket(e); } }
/// <summary> /// /// </summary> /// <param name="e"></param> private void CloseClientSocket(SocketAsyncEventArgs e) { AsyncUserToken token = e.UserToken as AsyncUserToken; // 关闭与客户端关联的套接字 try { token.Socket.Shutdown(SocketShutdown.Send); } //如果客户端进程已关闭,则引发 catch (Exception) { } token.Socket.Close(); // 递减计数器以跟踪连接到服务器的客户端总数 Interlocked.Decrement(ref m_numConnectedSockets); // 释放SocketAsyncEventArg,以便其他客户端可以重用它们 m_readWritePool.Push(e); m_maxNumberAcceptedClients.Release(); Console.WriteLine("A client has been disconnected from the server. There are {0} clients connected to the server", m_numConnectedSockets); }
/// <summary> /// 此方法在异步接收操作完成时调用 /// 如果远程主机关闭了连接,则套接字将关闭。 /// 如果接收到数据,则将数据回显到客户端。 /// </summary> /// <param name="e"></param> private void ProcessReceive(SocketAsyncEventArgs e) { // 检查远程主机是否关闭了连接 AsyncUserToken token = (AsyncUserToken)e.UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { //增加服务器接收的总字节数 Interlocked.Add(ref m_totalBytesRead, e.BytesTransferred); Console.WriteLine("The server has read a total of {0} bytes", m_totalBytesRead); //将接收到的数据回显到客户端 e.SetBuffer(e.Offset, e.BytesTransferred); bool willRaiseEvent = token.Socket.SendAsync(e); if (!willRaiseEvent) { ProcessSend(e); } } else { CloseClientSocket(e); } }