0

我正在尝试在 C# 中构建一个套接字服务器,我遇到的一个问题是,当我将AsyncCallback传递给我的套接字的BeginReceive方法时,回调被调用得太快了,当我读取 IAsyncResult 的AsyncState属性时,我得到了 null。

我以为我已经通过添加“修复”了这个

.AsyncWaitHandle.WaitOne(100);

但问题仍然存在。谁能阐明我做错了什么?

我的代码如下(略):

   private void Main(){

        _listener.BeginAccept(new AsyncCallback(HandleConnection), null);
    }


    private void HandleConnection(IAsyncResult status)
    {
        SocketError socketRecieveError;

        _connectionSocket = _listener.EndAccept(status);
        _connectionSocket.BeginReceive(_receivedDataBuffer, 0, _receivedDataBuffer.Length, 0, out socketRecieveError,
                                      new AsyncCallback(HandleHandshake), _connectionSocket.Available);

        if(socketRecieveError !=  SocketError.Success)
            _logger.Log("Socket error: " + socketRecieveError);
    }


    private void HandleHandshake(IAsyncResult status)
    {

        status.AsyncWaitHandle.WaitOne(1000);

        int handshakeLength;

        try
        {
            handshakeLength = Convert.ToInt32(status.AsyncState); // <--- BOOOM
        }
        catch (Exception ex)
        {
            _logger.Log(ex.Message);
        }
 ..............
 }
4

1 回答 1

1

IAsyncResult 的 AsyncState 属性包含用户定义的对象,该对象包含有关异步操作 ( MSDN ) 的信息。这与调用异步操作时作为参数“state”提供的对象相同。

在您的代码中,您提供 _connectionSocket.Available 作为用户状态。我想你想为你的回调方法提供接收到的字节数?这不是正确的做法。

这将是正确的方法:

private void HandleConnection(IAsyncResult status)
{
    SocketError socketRecieveError;

    _connectionSocket = _listener.EndAccept(status);
    _connectionSocket.BeginReceive(_receivedDataBuffer, 0, _receivedDataBuffer.Length, 0, out socketRecieveError, new AsyncCallback(HandleHandshake), null);

    if(socketRecieveError !=  SocketError.Success)
        _logger.Log("Socket error: " + socketRecieveError);
}

private void HandleHandshake(IAsyncResult ar)
{
    int bytesReceived = _connectionSocket.EndReceive(ar);

    ....
}
于 2011-01-27T11:08:01.050 回答