0
votes

I need some help. I have a simple server-client application using C# TCPClient

The problem that I am having is that when a client sends a message to server, the server returns a 4 bytes response containing an number.

But, every 3 or 4 responses the bytes are in the same wrong place.

For example:

server response with a byte array containing an integer 243:

byte[0] => 243 byte[1] => 0 byte[2] => 0 byte[3] => 0

The client receives the 4 bytes as follows:

byte[0] => 0 byte[1] => 0 byte[2] => 243 byte[3] => 0

This is an integer number of 15925248 not 243.

Here's the snippet of server code. the code executes when client sends a message:

byte[4] resp = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(243), 0, resp, 0, 4);
clientStream.Write(resp, 0, resp.Length);
clientStream.Flush();

Here's the snippet of client code to receive:

Byte[] rec = new Byte[4] {0xx0, 0x00, 0x00, 0x00};
if (netStream.CanRead)
{
int numberOfBytesRead = 0;
do
{
numberOfBytesRead = netStream.Read(rec, 0, rec.Length);
} while (netStream.DataAvailable);
}

I have done the following: - verified that the server indeed is sending the byte array correctly.

I don't know what am I doing wrong here. Or is there a bug in my code or not.

1

1 Answers

1
votes

You retrieve the numberOfBytesRead but you don't check whether it actually received all four bytes. If for example the first received data was 3 bytes, the next byte will be read on a consecutive Read from the stream, 'shifting' the data.

You could fix this by changing the code into something like this:

byte[] rec = new byte[4];
int index = 0;
int remainingBytes = rec.Length;
while (remainingBytes > 0)
{
    int read = netStream.Read(rec, index, remainingBytes);
    if (read == 0) return DisconnectedBeforeReceiving4Bytes();
    remainingBytes -= read;
    index += read;
}