简体   繁体   English

编码简约消息的最佳方法

[英]Best way to encode minimalistic messages

I need to create a little client/server application that should transfer data like this: 我需要创建一个小的客户端/服务器应用程序,该应用程序应该像这样传输数据:

statistic <- command type identifier statistic <-命令类型标识符

15.23.63.12 <- Statistic for this IP address 15.23.63.12 <-该IP地址的统计信息

increase <- the kind of action that should be done with the address's statistic increase <-使用地址统计信息应执行的操作

6 <- Just some other parameters... 6 <-其他一些参数...

So there has to be one string that identifies the type of the command and then there should be some parameters depending on the command type. 因此,必须有一个字符串来标识命令的类型,然后根据命令的类型应该有一些参数。 This parameters are different but always primitive data types. 此参数不同,但始终是原始数据类型。 Most probably String, Short, Byte, Integer, and so on... 最有可能是String,Short,Byte,Integer等...

So there are instruction sets of different primitive data types. 因此,存在不同原始数据类型的指令集。

My question is: Is it the best way to wrap the socket's streams in DataInput/OutputStreams and just read/write from them? 我的问题是:这是将套接字的流包装到DataInput / OutputStreams中并从中读取/写入的最佳方法吗? Or is it better to save the messages into a byte array and then wrap this byte array in a ByteArrayInputStream and wrap the ByteArrayInputStream in a DataInputStream that I can read from? 还是将消息保存到字节数组中,然后将此字节数组包装在ByteArrayInputStream中,然后将ByteArrayInputStream包装在我可以读取的DataInputStream ,是否更好? Or should I wrap the byte array in a ByteBuffer ? 还是应该将字节数组包装在ByteBuffer

And if I wanted to encrypt my messages, would I have to save them as a byte array, then decrypt the byte array and then wrap it into some kind of data reader? 而且,如果我想加密我的消息,是否需要将它们另存为字节数组,然后解密该字节数组,然后将其包装到某种数据读取器中?

You could do this more "efficient" if that's what you're asking. 如果您要这样做,则可以更“高效”地进行操作。

I would model the command type modifier with bytes, provided that you don't have more than 255 distinct modes: 如果您没有超过255个不同的模式,我将使用字节为命令类型修饰符建模:

byte cmd_statistic = 0;
byte cmd_nonstatistic = 1;

Then each ip address could be modeled as 4 bytes, like this: 然后可以将每个IP地址建模为4个字节,如下所示:

byte[] ip0 = new byte[]{15, 23, 63, 12};
byte[] ip1 = new byte[]{15, 23, 63, 13};

The action could also be bytes: 该动作也可以是字节:

byte action_increase = 0;
byte action_decrease = 1;

And if you could model the last parameters as bytes you could get away with just using InputStreams (is) and OutputStreams like this: 而且,如果您可以将最后一个参数建模为字节,则只需使用InputStreams(is)和OutputStreams就可以了:

// Code for reading, writing is very similar
byte cmd = (byte)is.read();

byte[] ip = new byte[4];
is.read(ip, 0, 4);

byte action = (byte)is.read();
byte extra  = (byte)is.read();

This is also easy to keep in a large byte[] and that is easier to use for encryption 这也很容易保存在大字节[]中,并且更易于用于加密

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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