问题
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