字符缺失

发布于 2024-11-04 15:58:07 字数 494 浏览 0 评论 0原文

我正在尝试向远程设备发送 JSON 请求,然后该设备返回 JSON 响应。

我使用的代码是这样的:

TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("someip"), someport);
NetworkStream stream = client.GetStream();
byte[] myWriteBuffer = Encoding.ASCII.GetBytes("some JSON");
stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
BinaryReader r = new BinaryReader(stream);
Console.WriteLine(r.ReadString())

此代码成功发送 JSON 字符串,接收响应,但该响应仅显示 123 个字符,这意味着它剪切了一些字符......

我做错了什么

I'm trying to send a JSON request to a remote device that then returns a JSON response.

The code I've used is this:

TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("someip"), someport);
NetworkStream stream = client.GetStream();
byte[] myWriteBuffer = Encoding.ASCII.GetBytes("some JSON");
stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
BinaryReader r = new BinaryReader(stream);
Console.WriteLine(r.ReadString())

This code successfully sends the JSON string, receives the response, but that response only shows 123 characters, meaning that it cuts some chars...

What am I doing wrong

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尐偏执 2024-11-11 15:58:07

BinaryReader / BinaryWriter 不一定是写入任意流的正确工具;特别是,他们选择一种带有长度前缀的特定字符串编码方式。如果这不是您的远程设备所期望的,它将失败。

我将直接使用 Stream 以及 ReadWrite

特别是,{ 的 ASCII 值是 123,因此看起来 BinaryReader 错误地从 JSON 左大括号中获取了“长度”。

BinaryReader / BinaryWriter are not necessarily the right tools for writing to an arbitrary stream; in particular, they choose a specific way of encoding strings, with a length-prefix. If this is not what your remote device is expecting, it will fail.

I would just use the Stream directly, with Read and Write.

In particular, { is 123 in ASCII, so it looks BinaryReader is incorrectly taking the "length" from the opening JSON brace.

街角卖回忆 2024-11-11 15:58:07

可能是编码/解码问题,我会像这样更改你的代码

TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("someip"), someport);
NetworkStream stream = client.GetStream();
byte[] myWriteBuffer = Encoding.ASCII.GetBytes("some JSON");
stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);

byte[] readBuffer = stream.GetBuffer();
Console.WriteLine(Encoding.ASCII.GetString(bytes));

Probably an encoding/decoding issue, I would change your code like so

TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("someip"), someport);
NetworkStream stream = client.GetStream();
byte[] myWriteBuffer = Encoding.ASCII.GetBytes("some JSON");
stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);

byte[] readBuffer = stream.GetBuffer();
Console.WriteLine(Encoding.ASCII.GetString(bytes));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文