Hi,
I need to asynchronously read from a network (TCP) stream, and I am
having trouble with retrieving whole blocks; I get a break in the data
block every 1460 bytes which relates to network packet sizes I guess.
To get this fixed, I am trying to follow an example in the MSDN, which
pretty much resembles what I want to do. Since the code (I can't do
this in a static class for example) is not 100% what I need, I
certainly would like to understand what I am doing, but I guess I am
lacking some fundamentals of asynchronous programming since I simply
do not understand the code snippet. Here it is:
public static void myReadCallBack( IAsyncResult ar ){
NetworkStream myNetworkStream = (NetworkStream) ar.AsyncState;
byte[] myReadBuffer = new byte[1024];
String myCompleteMessa ge = "";
int numberOfBytesRe ad;
numberOfBytesRe ad = myNetworkStream .EndRead(ar);
myCompleteMessa ge =
String.Concat(m yCompleteMessag e,
Encoding.ASCII. GetString(myRea dBuffer, 0, numberOfBytesRe ad));
// message received may be larger than buffer size so loop through
until you have it all.
while(myNetwork Stream.DataAvai lable){
myNetworkStream .BeginRead(myRe adBuffer, 0,
myReadBuffer.Le ngth,
new
AsyncCallback(N etworkStream_AS ync_Send_Receiv e.myReadCallBac k),
myNetworkStream );
}
// Print out the received message to the console.
Console.WriteLi ne("You received the following message : " +
myCompleteMessa ge);
}
I wonder, how myCompleteMessa ge can ever add up to the complete
message, since it will be reinitialized at every callback, won't it?
If somebody can help me to understand this (what happens
"while(myNetwor kStream.DataAva ilable){...}") , I would be most
grateful.
Best regards
DC