简体   繁体   中英

Reading/Writing JSON from/to a socket

I am using the gson library to convert some classes to JSON and send them down a socket.

Currently I can convert to a string and the write the string to the socket using a BufferedWriter . I can read the other end using a BufferedReader to a string and then parse the string to a JSON object. I have to send the length of the JSON string down the pipe first before the JSON object.

I can't help but think there must be a more efficient way of doing this using some sort of JSON stream reader/writer to avoid reading/writing to a string first. Assuming there is a way to read and write straight to the stream, how would you handle the case of badly formed JSON being sent.

What is the best way to write this and read this from the socket?

This is a learning exercise, so although I could come up with something that works, I am looking for the "proper" solution.

I would recommend developing a new protocol for just the Json object (message).

That could be something like:

&&DeterminedBeginChars&& Json Message &&DeterminedEndChars&&

This being over the socket. This would allow you to know when a Json message is being sent, and what's its length. This way you'll avoid any parsing with String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM