Answer the question
In order to leave comments, you need to log in
How to map packets by opcode?
I need theoretical information that will direct me in the right direction (hussars be silent! :)
The format of packets sent over the network in my program is determined by the structure [size][opcode][payload_data] and all packet classes are an implementation of the IPacket interface in order to implement a certain set of Parse methods, Create &etc.
The class into which the data from the packet will be mapped is determined by the opcode.
Here the question arose how to map packets by opcode?
I immediately dismissed the footcloth from the switch-case. I want an easily extensible concise solution.
There was an idea to use a dictionary of the form
dictionary[opcode]{ payload_size, packet_name, delegate -> IPacket SomePacket.Parse(byte[] buffer) }
, and pull the Parse method described in the interface. The problem is that the returned object is IPacket and you need to explicitly cast it to SomePacket. And this is again a huge switch-case footcloth, and the dictionary itself must be described, but I don’t know other ways (or the slow System.Reflection, but it’s damn slow + again a dictionary). Answer the question
In order to leave comments, you need to log in
Professionals use -> switch-case for int which are in order. Then this in IL becomes not a ceq sequence, but a switch , which then becomes a jump table .
This is the fastest method in terms of performance. Further, in order not to write this footcloth yourself, you can choose one of 2 options:
- dynamic generation of IL in runtime through DynamicMethod
- static code generation, through Roslyn from sources, T4 from compiled code
Did I understand the task correctly? Need to get a specific class instance by opcode (number)?
It seems that the most flexible and extensible way would be a factory, inside which is a switch (in one single place).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question