I work with a simple binary protocol. Each packet consists of 10 bytes. The first byte determines the type of packet. There are many types of packages (~ 50).
I want to write a general parser for this protocol, which is independent of packet processing. Therefore, the analyzer must determine the type of packet and place the data in an instance of the corresponding packet class that contains the protocol data. For example, given the following classes: When the parser detects packet type 1 → new Type1 () and reads raw bytes and sets the temperature and humidity. Similarly for package type 2 and all other package types.
class Packet { byte[] raw; } class Type1 extends Packet { int temperature; int humidity; } class Type2 extends Packet { DateTime sunrise; DateTime sunset; }
Since there are so many types of packages, but very little is used for each application, it should be possible to register certain types before starting parsing. All other packet types are ignored.
I plan to have PacketParser for each type of package. Maybe I need a handler class for each type. For instance:.
abstract class Type1Parser { abstract void handle(Type1 packet); } class Type1Parser extends PacketParser {
How to connect parser and handler? Above the naive approach: The program needs to implement Type1Handler and set the static variable Type1Parser.type1Handler.
Then the main parser might look like this:
class MainParser { Type1Parser type1 = new Type1Parser(); Type2Parser type2 = new Type2Parser(); ... void parse(byte[] packet) { switch(packet[0]) { case 1: type1.parse(packet); break; case 2: type2.parse(packet); break; ... } } }
However, this, apparently, 1) a lot of very similar lines of code 2) a lot of overhead, since the entire batch parser is created and is called for each batch call (), even if the handler is not registered.
Any ideas on improving this code?
Note. Parsing should be transparent to the program. The analysis code must remain inside the parsing library. Therefore, ideally, the program only “knows” the TypeXHandler and TypeX classes.