我正在使用 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);
}
}