Binary streams in c#, please help [RESOLVED]
Hi,
I've got a weird problem with a while loop in c#. It seems like it's behaving like an IF statement :confused:
I have this code:
Code:
Byte[] bytesRead = new Byte[10];
while((intBytes = myTcpClientStream.Read(bytesRead, 0, bytesRead.Length)) > 0){
binaryWriter.Write(bytesRead, 0, intBytes);
bytesRead = new Byte[10];
}
//etc.
The total amount of bytes being written here, is 51. It repeats 6 times, which is good. But then it gots stuck or something at the while statement. It never reaches the statements after the loop.
I tried to change the number of bytes that will be read to 51 or even to 1, but no luck. For some reason, the code doesn't know what to do if the evaluation for the loop is false.
Strangely, this works well:
Code:
Byte[] bytesRead = new Byte[51];
intBytes = myTcpClientStream.Read(bytesRead, 0, bytesRead.Length);
binaryWriter.Write(bytesRead, 0, intBytes);
// etc.
But, obviously, this last code isn't very generic... :bigyello:
So, now I got stuck here. Any suggestions are welcome! Maybe I did something wrong with the syntax? Simple while loops (like: while(x == true){ x = false; }) do work fine.
I'm using .NET Framework 1.1, VS.NET 2003, C# 1.1
Re: Binary streams in c#, please help
I found out the thing that causes the 'crash'.
It is the System.IO.Stream where I'm reading data from, that makes my app hang:
Code:
//somewhere in the beginning of my function:
Stream myStream = myTcpClient.GetStream();
//... then we get the while loop
int intBytes = 0;
byte[] readBytes = new byte[10];
while((intBytes = myStream.Read(readBytes,0,readBytes.Length)) != 0){
//...
}
What happens, is that this Stream object reads all sizes of byte buffers correct. But when it has passed the end of the stream, it doesn't return!
So what do I have to do to make this thing work?? Is there a way to pass this issue? Please help.
Re: Binary streams in c#, please help
Hi there,
Now I fixed my problem... and it took me so long to find it on the Internet :sick:
The problem lays in the Stream object:
Code:
//the TcpClient.GetStream() method returns a NetworkStream object
//My sample parsed it into a Stream object, now I use NetworkStream :-)
NetworkStream myNStream = myTcpClient.GetStream();
int intBytes = 0;
byte[] readBytes = new byte[10];
//And another approach to the while loop
do{
intBytes = myNStream.Read(readBytes,0,readBytes.Length);
myBinaryWriter.Write(readBytes,0,readBytes.Length);
readBytes = new byte[readBytes.Length];
intBytes = 0;
} while(myNStream.DataAvailable);
This code does the trick, without hanging!