1

我正在使用 SocketAsyncEventArgs,我每秒只能执行几次接受(我不知道为什么)。

如何最大化每秒接受的数量?我应该多次调用 Accept(null) 吗?

代码:在监听套接字上调用 Listen 后,我调用 Accept(null),这是我的代码:

void Accept(SocketAsyncEventArgs acceptEventArg)
{
    if (acceptEventArg == null)
    {
        acceptEventArg = new SocketAsyncEventArgs();
        acceptEventArg.Completed += AcceptCompleted;
    }
    else
    {
        // socket must be cleared since the context object is being reused
        acceptEventArg.AcceptSocket = null;
    }

    bool willRaiseEvent = _listener.AcceptAsync(acceptEventArg);
    if (!willRaiseEvent)
    {
        Accepted(acceptEventArg);
    }
}

void AcceptCompleted(object sender, SocketAsyncEventArgs e)
{
    if (_onAccepted != null) _onAccepted(e);
}

void Accepted(SocketAsyncEventArgs e)
{
    if (!e.AcceptSocket.Connected) return;

    //1
    var acceptSocket = e.AcceptSocket;
    var readEventArgs = CreateArg(null, e.AcceptSocket, null);

    bool willRaiseEvent = true;
    if (acceptSocket.Connected)
        willRaiseEvent = acceptSocket.ReceiveAsync(readEventArgs);

    //2
    Accept(e);

    //3
    if (!willRaiseEvent)
    {
        Received(readEventArgs);
    }
}
4

1 回答 1

0

默认情况下有连接限制。您可以使用 DefaultConnectionLimit http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit.aspx更改它

于 2012-11-04T19:10:31.200 回答