指定参数超出有效值范围,无法在 C# 中从网络获取数据

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

我正在尝试向传感器发送命令并使用以下代码从中获取数据:

 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();

        }

在这一行 int bytesSend = nwStream.Read(buffersend, 0, client.ReceiveBufferSize); 我得到了这个错误:

Specified argument was out of the range of valid value

buffersend 是 52 而 client.ReceiveBufferSize 是 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;
        }

我是 c# 套接字编程的新手

而不是这个

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

我想你只是想要这个。

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

没有必要为了用 GetBytes 的结果替换它而新建一个数组。另外我不认为你想读入 buffersend,你只是想写它。你后面的代码将读入 buffer.

根据 NetworkStream.Read

的文档,您得到异常的原因是 buffersend 的长度小于 client.ReceiveBufferSize