comp2000
asked on
NetworkStream.Read long messages problem
Hi,
I am quite novice to networks and tcp/ip so it might be a silly one.
My problem is that whenever I send long messages over WAN from a client and read them using NetworkStream.Read in the server, I'm not reading a complete message but only part of it (The buffer is bigger than the byte array actually read) which causes the messsage parser to fail.
Am I responssibe for checking that the whole message arrived by using NetworkStream.Read over and over until the whole message was received? Doesn't TcpClient know whether the message has arrived successfully? What are the common patterns for handling similar situations? Code snippets would be appritiated!
I am quite novice to networks and tcp/ip so it might be a silly one.
My problem is that whenever I send long messages over WAN from a client and read them using NetworkStream.Read in the server, I'm not reading a complete message but only part of it (The buffer is bigger than the byte array actually read) which causes the messsage parser to fail.
Am I responssibe for checking that the whole message arrived by using NetworkStream.Read over and over until the whole message was received? Doesn't TcpClient know whether the message has arrived successfully? What are the common patterns for handling similar situations? Code snippets would be appritiated!
ASKER
Thanks, it does seem like a good solution and I'll give it a try but how exactly do I know the data size? Do I have to add my own header to the data? Is there a common pratice for adding a header to your data?
Also, how do I mark the end of the message and how do I recover from a corrupted message?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
//***Try this function which will read data exactly the given size in a loop
private void ReadData(Socket socket, ref byte []buffer, int dataSize)
{
int size,index = 0;
if(buffer == null || buffer.Length < dataSize)
buffer = new byte[dataSize];
while(dataSize > 0)
{
size = socket.Receive(buffer,inde
if(size == 0)
throw(new Exception("Connection closed"));
dataSize -= size;
index += size;
}
}