0
votes

I want to receive bytes into an array from tcp client. I've an array of bytes dataToRecieve, in which I'm receiving those bytes.

But I've got some problems here, can anyone check my code:

while (true) {
    try {                           
       Socket handler = mainSocket.Accept();
       byte[] dataToRecieve = new byte[handler.ReceiveBufferSize];
       int[] dataArray = new int[1024];
       handler.Receive(dataToRecieve);
       //////SOME CODE
       int i = handler.Send(msg);
       handler.Shutdown(SocketShutdown.Both);
       handler.Close();
    }
catch(Exception) {}
--------//////some code

Now I want to receive bytes into byte array & than convert it into the int array (however the data should be in an int array)........

1
what problem are you having? - C-va
One immediate issue - you're not looking at the return value for Socket.Receive. You are not guaranteed that a call to Send() at one end, with a particular number of bytes will result in one call to Receive() gaining that same number of bytes. - Damien_The_Unbeliever

1 Answers

0
votes

Well, your code already has a problem here:

handler.Receive(dataToRecieve);

You're ignoring the value returned by Receive, to tell you how many bytes were actually read. That's almost always a bad idea. Likewise you're assuming you receive all the information you need in a single call. Usually you'd either have to loop until you'd read all the data - either by knowing that you expect a certain amount, or by reading until there is no more data.

Once you've got the data into a byte array, converting it into an integer array depends on the format in the byte array. You may be able to just use Buffer.BlockCopy, but that's only if the endianness in the byte array matches the endianness in memory. Alternatively, you can simply create an array of the right size, and write a loop:

int[] integers = new byte[size / 4];
for (int i = 0; i < integers.Length; i++)
{
    integers[i] = BitConverter.ToInt32(bytes, i * 4);
}

However, again you need to consider the endianness. My MiscUtil library has an EndianBitConverter class which allows you to specify the endianness of your data.