Stack overflow when using the System.Net.Sockets.Socket.AcceptAsync model

后端 未结 4 1625
太阳男子
太阳男子 2021-02-13 10:44

With respect to C# and .NET\'s System.Net.Sockets.Socket.AcceptAsync method, one would be required to handle a return value of \"false\" in order to handle the immediately avail

4条回答
  •  渐次进展
    2021-02-13 11:37

    newSocket.Send(Encoding.ASCII.GetBytes("Hello socket!")); 
    newSocket.Disconnect(false); 
    newSocket.Close(); 
    

    The problem with this snippet above is that this will block your next accept operation.

    A better way is like this:

    while (true)
    {
       if (e.SocketError == SocketError.Success)
       {
          //ReadEventArg object user token
          SocketAsyncEventArgs readEventArgs = m_readWritePool.Pop();
          Socket socket = ((AsyncUserToken)readEventArgs.UserToken).Socket = e.AcceptSocket;
    
          if (!socket.ReceiveAsync(readEventArgs))
             ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessReceiveEx), readEventArgs); .
        }
        else
        {
           HadleBadAccept(e);
        }
    
        e.AcceptSocket = null;
    
        m_maxNumberAcceptedClients.WaitOne();
        if (listenSocket.AcceptAsync(e))
           break;
    }
    

提交回复
热议问题