V
V
Vlad2018-11-21 14:21:25
.NET
Vlad, 2018-11-21 14:21:25

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).
How is mapping implemented by professionals?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
shai_hulud, 2018-11-21
@shai_hulud

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

D
Denis Zagaevsky, 2018-11-21
@zagayevskiy

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).

B
basrach, 2018-11-21
@basrach

Implemented by professionals through switch-case - the most understandable and effective way for those who will support. As an exercise, or if you are not working in a team, you can try through code generation, reflection, and whatever else comes to mind.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question