ProtocolEngine is a binary protocol decoder or encoder, its work just like struct in C language,while the ProtocolEngine also provide much more advanced features.
To use ProtocolEngine you just need to include the com-github-ioprotocol-x.x.x.jar file in the classpath.
If you are using Maven just add the following dependency to your pom.xml:
<dependency>
<groupId>com.github.ioprotocol</groupId>
<artifactId>com-github-ioprotocol</artifactId>
<version>1.2.0</version>
</dependency>ProtocolEngineengin = newProtocolEngine();
JavaBeanbean = engine.decode(byte[] buf, JavaBean.class);
// orbyte[] buf = engine.encode(bean);Now we use a simple binary protocol begin our travel.
The binary protocol like this:
+--------+---------+--------+----------------+
| Header | Version | Length | Content |
| 0x2882 | 0x01 | 0x000B | "HELLO, WORLD" |
+--------+---------+--------+----------------+First we need define a java class like this:
importcom.github.io.protocol.annotation.AsciiString;
importcom.github.io.protocol.annotation.ByteOrder;
importcom.github.io.protocol.annotation.Number;
publicclassProtocolTest {
@Number(width = 16, order = ByteOrder.BigEndian)
privateintheader;
@Number(width = 8)
privateintversion;
@Number(width = 16, order = ByteOrder.BigEndian)
privateintcontentLength;
@AsciiString(length = "getContentLength")
privateStringcontent;
publicintgetHeader() {
returnheader;
}
publicvoidsetHeader(intheader) {
this.header = header;
}
publicintgetVersion() {
returnversion;
}
publicvoidsetVersion(intversion) {
this.version = version;
}
publicintgetContentLength() {
returncontentLength;
}
publicvoidsetContentLength(intcontentLength) {
this.contentLength = contentLength;
}
publicStringgetContent() {
returncontent;
}
publicvoidsetContent(Stringcontent) {
this.content = content;
}
}then we can decode or encode the protocol like this:
@Testpublicvoidtest() throwsException {
ProtocolEngineengine = newProtocolEngine();
ProtocolTesttest = newProtocolTest();
test.setHeader(0x2882);
test.setVersion(1);
test.setContentLength(12);
test.setContent("HELLO, WORLD");
// we encode the ProtocolTest object to byte buffer.byte[] buf = engine.encode(test);
System.out.println(HexStringUtil.toHexString(buf));
// print msg:// 288201000C48454C4C4F2C20574F524C44// ok, now we decode the ProtocolTest object from byte[] array.ProtocolTesttestDecode = engine.decode(buf, ProtocolTest.class);
System.out.println(testDecode.toString());
// print msg:// ProtocolTest{header=10370, version=1, contentLength=12, content='HELLO, WORLD'}// wow... is it work?
}For more usage examples check the tests. Please check the documention. There are lots of cool things you should know.
While you find bug or have good idea, welcome email to me.
Email:xushy@yahoo.com
QQ:845158228