我每个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
回调!以前,我曾尝试对SocketAsyncEventArgs
和SendAsync
使用单个ReceiveAsync
,但行为是相同的!
为什么以及如何解决此问题?我看过这样的东西:
bool raised = e.AcceptSocket.SendAsync(args);
if(!raised) Sent(args);
但是我不想那样做。