问题
I want to build a Java server that accepts TCP streams that are completely platform independent, so that the client could be written in any other language like C++, PHP, ActionScript or anything else.
However, when I want to write different primitives to the stream like int, short etc. I must take care for the right integer length and if the integer is signed or unsigned. This is a problem, because the integer byte length varies strongly across different platforms, e.g. PHP integers have different size on 32 and 64 bit machines.
For this reason it might be reasonable to send only text and not integer values, because every machine interprets text in the same way if the text uses the same char set and byte order. Hence, the server can only use DataInputStream.readUTF() if it should read platform independent data.
I'm not sure if my arguments are correct, but if I should be wrong please correct me.
回答1:
While you can send text, you shouldn't use writeUTF/readUTF as this is a specific format. i.e. an unsigned short
length followed by the UTF characters.
The reason text can be used is because you expect to parse each byte at a time, you can do exactly the same with binary (and it's is usually much faster)
The biggest difference is that text is much easier to read and debug. For this reason alone I suggest making your first protocol text based. I would only suggest doing binary protocols when you are much more confident you can debug protocol errors.
回答2:
Even DataInputStream.readUTF() is not an universal feature. It uses rather complex encoding.
Find data format that already has client libraries for most popular languages, e.g. Thrift or Protocol Buffers.
来源:https://stackoverflow.com/questions/17042731/java-receiving-platform-independent-tcp-streams