SocketAsyncEventArgs SendAsync callback doesn't work

自古美人都是妖i 提交于 2020-01-25 11:57:13

问题


I've two SocketAsyncEventArgs per Client like this:

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();
}

When Client sends data, Received function gets called and in Received function I'm sending whatever it's received to all connected Clients like this:

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);
}

All connected Clients receives data from server BUT it doesn't invoke the Sent callback! Previously, I'd tried with a single SocketAsyncEventArgs for both SendAsync and ReceiveAsync and the behavior was same!

Why and how to solve this problem? I've seen something like this:

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

BUT I don't want to do it manually like that.

来源:https://stackoverflow.com/questions/58638734/socketasynceventargs-sendasync-callback-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!