字符缺失
我正在尝试向远程设备发送 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BinaryReader
/BinaryWriter
不一定是写入任意流的正确工具;特别是,他们选择一种带有长度前缀的特定字符串编码方式。如果这不是您的远程设备所期望的,它将失败。我将直接使用
Stream
以及Read
和Write
。特别是,
{
的 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, withRead
andWrite
.In particular,
{
is 123 in ASCII, so it looksBinaryReader
is incorrectly taking the "length" from the opening JSON brace.可能是编码/解码问题,我会像这样更改你的代码
Probably an encoding/decoding issue, I would change your code like so