人物缺失

时间:2011-05-04 08:57:31

标签: c# binary

我正在尝试向远程设备发送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个字符,这意味着它会削减一些字符...

我做错了什么

2 个答案:

答案 0 :(得分:4)

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

我会直接使用Stream ReadWrite

特别是{在ASCII中是123,所以看起来BinaryReader错误地从开放的JSON括号中取出“长度”。

答案 1 :(得分:0)

可能是编码/解码问题,我会改变你的代码

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