Java: Receiving platform independent TCP streams [closed]

本小妞迷上赌 提交于 2019-12-11 19:44:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!