3

こんにちは男の子と女の子。

TCP/IP を介してサーバーと通信し、任意の数の raw バイトを送受信する端末ベースのクライアント アプリケーションを開発しています。各バイトは、さらに使用するために、これらのコマンドを表す Java クラスに解析する必要があるコマンドを表します。

これらのバイトを効率的に解析する方法について質問します。ネストされた if と switch-cases の束で終わりたくありません。

これらのコマンドのデータ クラスはすぐに使用できます。解析を行う適切な方法を理解する必要があるだけです。

仕様の例を次に示します。

バイト ストリームは、たとえば、[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]

最初のバイトは 0x01 で、これは 1 バイトのみを含むヘッダーの開始です。

2 つ目は、特定のコマンドのバイト数である長さです。ここでも 1 バイトのみです。

次は、最初のバイトがコマンド (この場合は 0x02) である任意のコマンドであり、コマンドに含まれる n 個のバイトが続きます。

後で。最後に、チェックサム関連のバイトがあります。

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;
}

}
4

4 に答える 4

2

そのhttps://github.com/raydac/java-binary-block-parserのJBBPライブラリを試すことができます

@Bin class Parsed { byte header; byte command; byte [] data; int checksum;}
Parsed parsed = JBBPParser.prepare("byte header; ubyte len; byte command; byte [len] data; int checksum;").parse(theArray).mapTo(Parsed.class);
于 2014-08-11T06:13:54.017 に答える
1

This is a huge and complex subject.

It depends on the type of the data that you will read.

  • Is it a looooong stream ?
  • Is it a lot of small independent structures/objects ?
  • Do you have some references between structures/objects of your flow ?

I recently wrote a byte serialization/deserialization library for a proprietary software.

I took a visitor-like approach with type conversion, the same way JAXB works.

I define my object as a Java class. Initialize the parser on the class, and then pass it the bytes to unserialize or the Java object to serialize.

The type detection (based on the first byte of your flow) is done forward with a simple case matching mechanism (1 => ClassA, 15 => ClassF, ...).

EDIT: It may be complex or overloaded with code (embedding objects) but keep in mind that nowadays, java optimize this well, it keeps code clear and understandable.

于 2013-09-13T12:15:55.963 に答える
0

ByteBufferバイトストリームの解析に使用できます - Java での ByteBuffer の使用は何ですか? :

byte[] bytesArray = {4, 2, 6, 5, 3, 2, 1};
ByteBuffer bb = ByteBuffer.wrap(bytesArray);
int intFromBB = bb.order(ByteOrder.LITTLE_ENDIAN).getInt(); 
byte byteFromBB = bb.get(); 
short shortFromBB = bb.getShort(); 
于 2016-08-31T12:14:05.600 に答える