Reputation: 4560
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
Upvotes: 2
Views: 683
Reputation: 8645
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));
Upvotes: 0
Reputation: 1063005
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.
Upvotes: 4