gpt4 book ai didi

java - 如何正确解析Java中的字节流

转载 作者:行者123 更新时间:2023-11-30 06:22:53 26 4
gpt4 key购买 nike

各位小伙伴们大家好。

我正在开发一个基于终端的客户端应用程序,它通过 TCP/IP 与服务器通信并发送和接收任意数量的原始字节。每个字节代表一个命令,我需要将其解析为代表这些命令的 Java 类,以供进一步使用。

我的问题是我应该如何有效地解析这些字节。我不想以一堆嵌套的 ifs 和 switch-cases 结束。

我已准备好这些命令的数据类。我只需要找出进行解析的正确方法。

这是一些示例规范:

Byte stream can be for example in integers:[1,24,2,65,26,18,3,0,239,19,0,14,0,42,65,110,110,97,32,109,121,121,106,228,42,15,20,5,149,45,87]

First byte is 0x01 which is start of header containing only one byte.

Second one is the length which is the number of bytes in certain commands, only one byte here also.

The next can be any command where the first byte is the command, 0x02 in this case, and it follows n number of bytes which are included in the command.

So on. In the end there are checksum related bytes.

表示 set_cursor 命令的示例类:

/**
* Sets the cursor position.
* Syntax: 0x0E | position
*/
public class SET_CURSOR {

private final int hexCommand = 0x0e;
private int position;

public SET_CURSOR(int position) {

}

public int getPosition() {
return position;
}

public int getHexCommnad() {
return hexCommand;
}

}

最佳答案

当像这样解析字节流时,最好使用的设计模式是命令模式。每个不同的命令都将充当处理程序来处理流中接下来的几个字节。

interface Command{

//depending on your situation,
//either use InputStream if you don't know
//how many bytes each Command will use
// or the the commands will use an unknown number of bytes
//or a large number of bytes that performance
//would be affected by copying everything.
void execute(InputStream in);

//or you can use an array if the
//if the number of bytes is known and small.
void execute( byte[] data);

}

然后您可以获得一个包含每个字节“操作码”的每个命令对象的映射。

Map<Byte, Command> commands = ...

commands.put(Byte.parseByte("0x0e", 16), new SetCursorCommand() );
...

然后您可以解析消息并根据命令执行操作:

InputStream in = ... //our byte array as inputstream
byte header = (byte)in.read();
int length = in.read();
byte commandKey = (byte)in.read();
byte[] data = new byte[length]
in.read(data);

Command command = commands.get(commandKey);
command.execute(data);

同一字节消息中可以有多个命令吗?如果是这样,您就可以轻松地将命令获取和解析包装在一个循环中,直到 EOF。

关于java - 如何正确解析Java中的字节流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18785702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com