C# reading wrong data from socket

Question

I'm trying to send a random words over one socket to another. I designed a simple protocol for the data management, every data package contains in it's first 4 bytes the length of the actual message(as bytes,),then the message itself.

This is the client code:

    private byte[] sendBuffer = new byte[1000];
    private Socket sSocket;
    private void WriteDataLength(int length)
    {
        sendBuffer[0] = (byte)(length);
        sendBuffer[1] = (byte)(length >> 8);
        sendBuffer[2] = (byte)(length >> 16);
        sendBuffer[3] = (byte)(length >> 24);
    }
    private void DoWork()
    {
        while (true)
        {
            string word = RandomString(random.Next(1, 10)); //generates a random string.
            byte[] toBytes = Encoding.ASCII.GetBytes(word); //converting the string to byte array.
            int length = toBytes.Length; // length of the actual data(the word length).
            WriteDataLength(length);//writing the word length in bytes.
            Buffer.BlockCopy(toBytes, 0, sendBuffer, 4, toBytes.Length);//copying the array which hold the word to the sendBuffer (start from the 4th byte).
            sSocket.Send(sendBuffer, length+4 , SocketFlags.None);//send +4 bytes for the length prefix.        
        }
    }
    private static Random random = new Random();         
    public static string RandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        TcpClient tcpClient = new TcpClient();
        tcpClient.Connect("localhost", 10);
        sSocket = tcpClient.Client;
        Thread th = new Thread(DoWork);
        th.Start();
    }

As you see, i generate a random word,write it's first 4 bytes(simply shift the bits) and then copying it to the sendBuffer.

Server code:

    private byte[] recieveBuffer = new byte[1000];
    TcpListener tListener;
    Socket rSocket;
    private int readData()
    {
        rSocket.Receive(recieveBuffer, 0, 4, SocketFlags.None); //read the first 4 bytes
        int size = getDatalength(); //reassemble the bytes to the original value.
        int dataleft = size;
        int totalread = 4; //read already 4 bytes.
        int recv;
        while (totalread < size)
        {
            recv = rSocket.Receive(recieveBuffer, totalread, dataleft, 0);
            if (recv == 0) //stop reading
            {
                break;
            }
            totalread += recv;
            dataleft -= recv;
        }
        return size;
    }


    private int getDatalength()
    {
        int length = recieveBuffer[0] | recieveBuffer[1] << 8 | recieveBuffer[2] << 16 | recieveBuffer[3] << 24;
        return length;
    }
    private void DoWork()
    {
        while (true)
        {
            int length = readData();
            byte[] word = new byte[length]; //initializing a new array to hold the word
            Buffer.BlockCopy(recieveBuffer, 4, word, 0, length); //copying to the recieveBuffer from the 4th place( first 4 bytes are always length header).
            string result = Encoding.ASCII.GetString(word);
            Console.WriteLine(result);
        }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        tListener = new TcpListener(IPAddress.Any, 10);
        tListener.Start();
        rSocket = tListener.AcceptTcpClient().Client;
        Thread th = new Thread(DoWork);
        th.Start();

    }

In the server side,i read the first 4 bytes to get the length(so i can know how much do i have to read),then i start looping until the end of the data size.

I actualy dont know how to explain this, it works for 2 or 3 seconds,then the Server throws a System.ArgumentOutOfRangeException expection in this line:

recv = rSocket.Receive(recieveBuffer, totalread, dataleft, 0);

I debugged this and found the size variable holds very large numbers...(few millions for example),so i guess the problem is by reading the first 4 bytes...

I also tried to output the first 4 values of the recieveBuffer and they were different from the values in the client side..(when the exception throwed,by then they were the same).

I'm not sure what's wrong here.. i'll appreciate every help.

Thanks.


Show source
| c#   | arrays   | bit-manipulation   | sockets   2016-12-31 21:12 0 Answers

Answers to C# reading wrong data from socket ( 0 )

Leave a reply to - C# reading wrong data from socket

◀ Go back