I'm writing a simple socket client which uses only one socket. So I figured I could reuse a single SocketAsyncEventArgs for all receive operations. It's working fine as long as the socket is connected. When the server disconnects, the client will enter a infinite receive loop spamming "Receive Success" in the console.
Shouldn't e.SocketError != SocketError.Success be true when the socket is disconnected?
Here is part of the code:
private void Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
status = 0;
System.Console.WriteLine(e.LastOperation + " " + e.SocketError);
if (status == 1)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
ProcessConnect(e);
break;
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
ProcessSend(e);
break;
default:
status = 0;
break;
}
}
if (status != 1)
CloseSocket();
}
private void ProcessReceive(SocketAsyncEventArgs e)
{
if (!socket.ReceiveAsync(e))
Completed(null, e);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…