Asynchronous socket & recursive receiving
Hi, all,
I have seen in so many web artices that passing a
delegated function into a BeginReceive socket method, and
then in the function recursively receiving data.
But my experience with this has been that it does not
work: (basically the receiving recursion hangs) Trying to
debug this, I can see that the recursive call does not
step into the recursive function --ReceiveCallBack()
except for the first time. Please help!
Please see the "////" comments ---
Thanks in advance
BILL
==============================
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
..... client is a connected socket,
.....
Receive(client);
receiveDone.WaitOne();
....
private static void Receive(Socket client) {
try {
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive( state.buffer, 0,
StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback( IAsyncResult ar ) {
try {
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0) {
state.sb.Append(Encoding.ASCII.GetString
(state.buffer,0,bytesRead));
////===============================================
client.BeginReceive
(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
//// my program hangs here when trying to get the rest of
data, what could be wrong?
} else {
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
.