Specified argument was out of the range of valid value to get data from network in c#

1.1k views Asked by At

I am trying to send a command to a sensor and get the data from it using this code :

 const int PORT_NO = 3000;
        const string SERVER_IP = "192.168.2.44";


            //---listen at the specified IP and port no.---
            IPAddress localAdd = IPAddress.Any;
            TcpListener listener = new TcpListener(localAdd, PORT_NO);
            Console.WriteLine("Listening...");
            listener.Start();

            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();
            NetworkStream nwStream = client.GetStream();

            //---write back the text to the client---
            byte[] buffersend = new byte[client.ReceiveBufferSize];

            buffersend = GetBytes("00010002000B0300010004C380");
            int bytesSend = nwStream.Read(buffersend, 0, client.ReceiveBufferSize);

           // Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffersend, 0, bytesSend);

            //---get the incoming data through a network stream---
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received : " + dataReceived);


            client.Close();
            listener.Stop();
            Console.ReadLine();

        }

in this line int bytesSend = nwStream.Read(buffersend, 0, client.ReceiveBufferSize); i got this error :

Specified argument was out of the range of valid value

the buffersend is 52 and the client.ReceiveBufferSize is 8192

static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

I am so new in c# socket programming

1

There are 1 answers

4
juharr On BEST ANSWER

Instead of this

byte[] buffersend = new byte[client.ReceiveBufferSize];
buffersend = GetBytes("00010002000B0300010004C380");
int bytesSend = nwStream.Read(buffersend, 0, client.ReceiveBufferSize);
nwStream.Write(buffersend, 0, bytesSend);

I think you just want this.

byte[] buffersend =  GetBytes("00010002000B0300010004C380");
nwStream.Write(buffersend, 0, buffersend.Length);

There is no need to new up an array just to replace it with the results of GetBytes. Also I do not think you want to read into buffersend, you just want to write it. Your latter code will then read into buffer.

The reason you are getting the exception is that buffersend has a length that is less than client.ReceiveBufferSize per the documentation for NetworkStream.Read