M
Mark Smith
Dear Readers,
I am in the process of implementing a non-blocking ASYNC TCP client
using the .Net socket class. I am a little confused by the MSDN
example. I have pasted the code here.
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so
far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
In the callback if the number of bytes read is zero the else branch is
used.
What conditions do you expect here? Ie will I come through here once
the reads finished or is this branch more to catch the remote end
point hanging up?
Could someone explain this a better as all my data appears to be read
correctly in the first branch.
Thanks
Mark
I am in the process of implementing a non-blocking ASYNC TCP client
using the .Net socket class. I am a little confused by the MSDN
example. I have pasted the code here.
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so
far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
In the callback if the number of bytes read is zero the else branch is
used.
What conditions do you expect here? Ie will I come through here once
the reads finished or is this branch more to catch the remote end
point hanging up?
Could someone explain this a better as all my data appears to be read
correctly in the first branch.
Thanks
Mark