Best Practices for Developing a Java Protocol Stack

What is the efficiency of the Java protocol protocol stack?

In this particular case, my Java application will β€œtalk” to a PC peripheral whose bus will transmit data in protocol format.

Example:

Imagine that in my protocol there is a message consisting of a single integer, a string and a list of integers:

class MyMessage { int filed1; String filed2; LinkedList<int> field3;} 

What I want as an end product is what allows me to do this:

 // Message to fill MyMessage msg = new MyMessage(); // InputStream with the data to bind InputStream stream = myPeripheralBus.getInputSTream(); msg.fill(stream); // Here, msg fields are filled with the values that were on the InputStream 
+4
source share
1 answer

The google protocol buffer design fits most of your requirements. other than the LinkedList data structure in field3, but since gpb has kept the order of duplicate values, I think this is enough for you.

Protocol buffers are a way of encoding structured data in an efficient but extensible format. Google uses protocol buffers for almost all of its internal RPC protocols and file formats.

step 1, install gpb from http://code.google.com/apis/protocolbuffers/ , read the docs.

step 2, define your message. proto:

 message UserDetail { required string id = 1; optional string nick = 2; repeated double money = 3; } 

step 3, use protoc compile.proto and create the file UserDetail.java.

 ... public interface UserDetailOrBuilder extends com.google.protobuf.MessageOrBuilder { // required string id = 1; boolean hasId(); String getId(); // optional string nick = 2; boolean hasNick(); String getNick(); // repeated double money = 3; java.util.List<java.lang.Double> getMoneyList(); } public static final class UserDetail extends com.google.protobuf.GeneratedMessage implements UserDetailOrBuilder ... 

step 4, a simple call

 UserDetail.parseFrom(input); User.UserDetail t.writeTo(output); 

gpb has a different language addon, check out http://code.google.com/p/protobuf/wiki/ThirdPartyAddOns

+2
source

All Articles