I have a server which I do not control. I would like to interact with it by sending JSON requests and receiving JSON responses via TCP/IP socket. Let's assume UTF8 encoding is used and I have an open TCP connection with attached NetworkStream or SslStream called stream
.
Sending part is simple and works perfectly:
var request = new TRequest();
JsonSerializer.Serialize(stream, request);
Ideally, I would like to receive a response in the following way:
TResponse response = JsonSerializer.Deserialize<TResponse>(stream);
This call hangs and there is a reason for that. It tries to do buffered reading from NetworkStream until the stream is finished, then it starts deserialisation (well, actually it splits it into chunks but it doesn't really matter here).
The problem is NetworkStream, in comparison to a file stream or something like that, is never ended (unless connection closed). On top of that I don't want to consume more data than really required for my object (to be able to read the following object from the same stream). That means workarounds that read network data to byte array first are not really helpful here.
JSON format contains all the information to indicate when the end of the object occurred, so I don't see any technical problem here.
What do I need to tell JsonSerializer
to read the stream byte by byte without any buffering (not caring about performance) and stop as soon as the whole object has been read. Is there a possibility to do something like this by properly configuring either JsonSerializer
or using it on top of some kind of non-buffering stream?