Esempio n. 1
0
 /// <summary>
 /// This method is invoked when an asynchronous send operation completes.
 /// The method issues another receive on the socket to read any additional data sent from the client
 /// </summary>
 private void ProcessSend(SocketAsyncEventArgs e)
 {
     if (e.SocketError == SocketError.Success)
     {
         // done echoing data back to the client     完成回传数据回到客户端
         AsyncUserToken token = (AsyncUserToken)e.UserToken;
         // read the next block of data send from the client     读取从客户端发送的下一个数据块
         bool willRaiseEvent = token.UserSocket.ReceiveAsync(e);
         if (!willRaiseEvent)
         {
             ProcessReceive(e);
         }
     }
     else
     {
         CloseClientSocket(e);
     }
 }
Esempio n. 2
0
        private void CloseClientSocket(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = e.UserToken as AsyncUserToken;

            // close the socket associated with the client
            try
            {
                token.UserSocket.Shutdown(SocketShutdown.Send);
            }
            // throws if client process has already closed
            catch (Exception) { }

            token.UserSocket.Close();

            // Free the SocketAsyncEventArg so they can be reused by another client
            Interlocked.Decrement(ref m_numConnectedSockets);
            m_maxNumberAcceptedClients.Release();

            Console.WriteLine("A client has been disconnected from the Server. There are {0} clients connected to the server", m_numConnectedSockets);

            // Free the SocketAsyncEventArg so they can be reused by another client
            m_readWritePool.Push(e);
        }
Esempio n. 3
0
        /// <summary>
        /// This method is invoked when an asynchronous receive operation completes.
        /// If the remote host closed the connection, then the socket is closed.
        /// If data was received then the data is echoed back to the client.
        /// </summary>
        /// <param name="e"></param>
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = (AsyncUserToken)e.UserToken;

            // e.BytesTransferred获取套接字操作中传输的字节数。
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                // 对两个 32 位整数进行求和并用和替换第一个整数,上述操作作为一个原子操作完成。
                Interlocked.Add(ref m_totalBytesRead, e.BytesTransferred);
                Console.WriteLine("Server : The server has read a total of {0} bytes", m_totalBytesRead);

                //echo the data received back to the client
                e.SetBuffer(e.Offset, e.BytesTransferred);
                bool willRaiseEvent = token.UserSocket.SendAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessSend(e);
                }
            }
            else
            {
                CloseClientSocket(e);
            }
        }