异步套接字 - 处理虚假socket.AcceptAsync值虚假、socket、AcceptAsync

由网友(坚毅之梦)分享简介:Socket类有一个方法.AcceptAsync它要么返回true或false。The Socket class has a method .AcceptAsync which either returns true or false.我还以为假返回值是一个错误条件,但样本中微软提供了异步套接字他们调用回调函数检...

Socket类有一个方法.AcceptAsync它要么返回true或false。

The Socket class has a method .AcceptAsync which either returns true or false.

我还以为假返回值是一个错误条件,但样本中微软提供了异步套接字他们调用回调函数检查失败后同步,如下所示:

I'd thought the false return value was an error condition, but in the samples Microsoft provide for Async sockets they call the callback function synchronously after checking for failure, as shown here:

public void StartAccept(SocketAsyncEventArgs acceptEventArg)
    {
        if (acceptEventArg == null)
        {
            acceptEventArg = new SocketAsyncEventArgs();
            acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
        }
        else
        {
            // socket must be cleared since the context object is being reused
            acceptEventArg.AcceptSocket = null;
        }

        m_maxNumberAcceptedClients.WaitOne();
        bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
        if (!willRaiseEvent)
        {
            ProcessAccept(acceptEventArg);
        }
    }

    /// <summary>
    /// This method is the callback method associated with Socket.AcceptAsync operations and is invoked
    /// when an accept operation is complete
    /// </summary>
    void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
    {
        ProcessAccept(e);
    }

他们为什么这样做呢?它违背了异步套接字的目的,并从返回停止方法。

Why do they do this? It defeats the purpose of asynchronous sockets and stops the method from returning.

推荐答案

从的 AcceptAsync方法说明:

返回假如果在I / O操作   同步完成。该   SocketAsyncEventArgs.Completed   事件e参数将不   提出和电子对象通过为   参数可以被立即检测   后在方法调用返回到   检索操作的结果。

Returns false if the I/O operation completed synchronously. The SocketAsyncEventArgs.Completed event on the e parameter will not be raised and the e object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation.

当它返回false你应该处理immedeatly新接受插座。

When it returns false you're supposed to process immedeatly the newly accepted socket.

阅读全文

相关推荐

最新文章