Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi, i want to read stream from networkstream as below...
in the below code myReadBuffer.length is is 1024.i want to read stream of 1024 bytes length into
myReadBuffer....but i am getting different bytes length into myReadBuffer some times 50 bytes,some times 360 bytes....if i put breakpoint and Thread.sleep(),it is working some times good(giving some more extra bytes into myReadBuffer).but if i run without breakpoint and without thread.sleep(2000) it is not giving output....any one can explain why it is so.....


if(myNetworkStream.CanRead){
byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;

// Incoming message may be larger than the buffer size.
do{
numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);

myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

}
while(myNetworkStream.DataAvailable);

// Print out the received message to the console.
Console.WriteLine("You received the following message : " +
myCompleteMessage);
}
else{
Console.WriteLine("Sorry. You cannot read from this NetworkStream.");
}
Posted
Updated 17-May-13 4:22am
v2
Comments
Sergey Alexandrovich Kryukov 17-May-13 10:24am    
I cannot see the problem at the moment, but using Sleep is pointless. Why?
—SA
s pullareddy 17-May-13 10:29am    
i am getting some partial data into myReadBuffer object.if i debug keeping breakpoint line by line i am getting some more extra data.but if i run without keeping breakpoint i am getting 0 bytes also some times....can you explain why so...
Sergey Alexandrovich Kryukov 17-May-13 10:47am    
This is called "race condition", read about it in Wikipedia, to start from...
—SA
s pullareddy 17-May-13 10:52am    
ok i will see and meet again..
AlphaDeltaTheta 17-May-13 21:39pm    
This happens if connection is closed before all 1024 bytes is transferred or on a network with poor latency

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900