SocketAsyncEventArgs SendAsync回调不起作用

时间:2019-10-31 07:37:47

标签: sendasync socketasynceventargs

我每个SocketAsyncEventArgs有两个Client,像这样:

void Accepted(object s, SocketAsyncEventArgs e)
{
    e.Completed -= Accepted;
    Client c = new Client()
    {
        SendArgs = e,
        RecvArgs = new SocketAsyncEventArgs()
    };
    c.RecvArgs.AcceptSocket = e.AcceptSocket;
    c.RecvArgs.Completed += Received;
    c.SendArgs.Completed += Sent;
    SetBuffer(c.RecvArgs, bufferLength);
    c.RecvArgs.AcceptSocket.ReceiveAsync(c.RecvArgs);
    Accept();
}

Client发送数据时,将调用Received函数,在Received函数中,我会将接收到的所有内容发送给所有已连接的Clients,如下所示:

void Received(object s, SocketAsyncEventArgs e)
{
    if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
    {
        int packetSize = BitConverter.ToInt32(e.Buffer);
        SetBuffer(e, packetSize);
        e.AcceptSocket.Receive(e.Buffer);

        foreach (var c in Clients)
        {
            c.SendArgs.SetBuffer(e.Buffer);
            c.SendArgs.AcceptSocket.SendAsync(c.SendArgs);
        }

        SetBuffer(e, bufferLength);
        e.AcceptSocket.ReceiveAsync(e);
    }
    else RemoveClient(e);
}

所有已连接的Clients从服务器BUT接收数据,但不调用Sent回调!以前,我曾尝试对SocketAsyncEventArgsSendAsync使用单个ReceiveAsync,但行为是相同的!

为什么以及如何解决此问题?我看过这样的东西:

bool raised = e.AcceptSocket.SendAsync(args);
if(!raised) Sent(args);

但是我不想那样做。

0 个答案:

没有答案