Java:接收平台无关的TCP流 [英] Java: Receiving platform independent TCP streams

查看:91
本文介绍了Java:接收平台无关的TCP流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个Java服务器,该服务器接受完全独立于平台的TCP流,以便可以使用其他任何语言(例如C ++,PHP,ActionScript或其他任何语言)编写客户端.

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.

但是,当我想向流中写入不同的原语(例如int,short等)时,我必须注意正确的整数长度以及该整数是带符号的还是无符号的.这是一个问题,因为整数字节长度在不同的平台之间变化很大,例如PHP整数在32位和64位计算机上的大小不同.

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.

由于这个原因,仅发送文本而不发送整数值可能是合理的,因为如果文本使用相同的字符集和字节顺序,则每台计算机都以相同的方式解释文本.因此,如果服务器应该读取平台无关的数据,则只能使用DataInputStream.readUTF().

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.

推荐答案

虽然您可以发送文本,但是不应使用writeUTF/readUTF,因为这是一种特定格式.即无符号short长度,后跟UTF字符.

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.

这篇关于Java:接收平台无关的TCP流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆