Esempio n. 1
0
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                StartAccept(e);
                return;
            }

            if (m_readWritePool.Count == 0)
            {
                e.AcceptSocket = null;
                m_maxNumberAcceptedClients.Release();
                StartAccept(e);
                return;
            }

            SocketAsyncEventArgs eventArgs       = m_readWritePool.Pop();
            AsyncUserToken       accpetUserToken = (AsyncUserToken)eventArgs.UserToken;

            if (!m_clients.TryAdd(accpetUserToken.ID, accpetUserToken))
            {
                m_readWritePool.Push(eventArgs);
                throw new Exception("Add same ID into m_clients");
            }

            // Get the socket for the accepted client connection and put it into the
            // ReadEventArg object user token
            accpetUserToken.AcceptSocket         = e.AcceptSocket;
            accpetUserToken.AcceptAsyncEventArgs = e;
            accpetUserToken.ReadAsyncEventArgs   = eventArgs;
            accpetUserToken.ConnectDateTime      = DateTime.Now;

            string ipClient = accpetUserToken.AcceptSocket.RemoteEndPoint.ToString();

            Console.WriteLine("Server : Client [ {0} ] connected. ID is [ {1} ] There are {2} clients connected to server", ipClient, accpetUserToken.ID, m_clients.Count);

            // As soon as the client is connected, post a receive to the connection
            bool willRaiseEvent = accpetUserToken.AcceptSocket.ReceiveAsync(eventArgs);

            if (!willRaiseEvent)
            {
                ProcessReceive(eventArgs);
            }

            // Accept the next connection request
            StartAccept(e);
        }
Esempio n. 2
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.AcceptSocket.ReceiveAsync(e);
         if (!willRaiseEvent)
         {
             ProcessReceive(e);
         }
     }
     else
     {
         CloseClientSocket(e);
     }
 }