异步套接字 - 处理虚假socket.AcceptAsync值 [英] Asynchronous Sockets - Handling false socket.AcceptAsync values

查看:858
本文介绍了异步套接字 - 处理虚假socket.AcceptAsync值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于异步套接字 - 处理虚假socket.AcceptAsync值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆