This is similar to my last question. I'm making a simple tcp/ip chat program and I'm having a little difficulty with the EndReceive Callback function. I pasted in Microsoft's implementation (see below) and what I've noticed is that if the message has been read in it's entirety it won't run the callback function until the next message is sent i.e. EndReceive will never return a 0. For example if I send a text message of 5 characters and the buffer size is 20, 'read' will be 5, I'll process the string and call BeginReceive, however BeginReceive doesn't run until the server sends another message. The else section is never reached because s.EndReceive never returns a 0. How would I know when data has been received completely?
public static void Read_Callback(IAsyncResult ar){
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;
int read = s.EndReceive(ar);
if (read > 0) {
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
new AsyncCallback(Async_Send_Receive.Read_Callback), so);
}
else{
if (so.sb.Length > 1) {
//All of the data has been read, so displays it to the console
string strContent;
strContent = so.sb.ToString();
Console.WriteLine(String.Format("Read {0} byte from socket" +
"data = {1} ", strContent.Length, strContent));
}
s.Close();
}
}