简体   繁体   中英

Best way for transfering files via socket in java

I have a BufferedReader object and a PrintWriter object. So I can work passing String objects made by json-io of any type (eg: List, Map, MyOwnClass)

My class have a byte[] attribute, this byte[] will keep a file bytes, such as an image.

The json generated of my class is very very big, obviously... Then i started to think that must have a better way to transfer files.

Should I change all the mechanism to transfer only byte[] instead of String ? Does someone know what is the mechanism used by chat programs? Should I reserve the first 20 bytes of the array for the message identification?

I would write it to the socket in binary :

Assuming a class with one String and one byte[] .

  1. The String
  2. The byte[]

On the other side you would do the exact opposite of this procedure.

I chose this binary approach over JSON because even though you could transmit the byte[] with JSON almost as efficiently as in binary, it would defeat the very purpose of JSON: being human-readable.

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