指定的参数超出了从c#中的网络获取数据的有效值范围
本文关键字:网络 获取 有效值 范围 数据 参数 | 更新日期: 2023-09-27 17:59:02
我正试图向传感器发送命令,并使用以下代码从中获取数据:
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
CCD_ 2是52并且CCD_ 3是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