O
O.B.
In the following code snippet, the thread successfully makes it to the
line where it waits for data to be received. Then the client closes the
connection. The thread wakes up and returns from the WaitOne()
operation. No exception is thrown when it loops and executes
BeginReceive() again. The WaitOne() operation returns immediately.
Thus, there's an endless loop.
How does one detect that the remote client has closed the connection in
this situation?
//
// Started as a new thread to handle data received on an
// open socket.
//
private void ReceiveDataEventLoop(Socket clientSocket) {
while (true) {
try {
ClientState clientState = new ClientState(clientSocket);
IAsyncResult result = clientSocket.BeginReceive(
clientState.Buffer,
0,
clientState.Buffer.Length,
SocketFlags.None,
new AsyncCallback(this.ReceiveDataCallback),
clientState);
// Wait for the EndReceive before issuing a new BeginReceive
// When the remote client closes the connection, this starts
// to return immediately. How to identify that remote client
// closed connection?
result.AsyncWaitHandle.WaitOne();
} catch (SocketException) {
removeSocket(clientSocket);
break;
} catch (Exception) {
removeSocket(clientSocket);
break;
}
}
}
line where it waits for data to be received. Then the client closes the
connection. The thread wakes up and returns from the WaitOne()
operation. No exception is thrown when it loops and executes
BeginReceive() again. The WaitOne() operation returns immediately.
Thus, there's an endless loop.
How does one detect that the remote client has closed the connection in
this situation?
//
// Started as a new thread to handle data received on an
// open socket.
//
private void ReceiveDataEventLoop(Socket clientSocket) {
while (true) {
try {
ClientState clientState = new ClientState(clientSocket);
IAsyncResult result = clientSocket.BeginReceive(
clientState.Buffer,
0,
clientState.Buffer.Length,
SocketFlags.None,
new AsyncCallback(this.ReceiveDataCallback),
clientState);
// Wait for the EndReceive before issuing a new BeginReceive
// When the remote client closes the connection, this starts
// to return immediately. How to identify that remote client
// closed connection?
result.AsyncWaitHandle.WaitOne();
} catch (SocketException) {
removeSocket(clientSocket);
break;
} catch (Exception) {
removeSocket(clientSocket);
break;
}
}
}