Proper way to communicate with socket

Is there any design pattern or something else for the network communication using Socket. I mean what i always do is :

  • I receive a message from my client or my server
  • I extract the type of this message (f.e : LOGIN or LOGOUT or CHECK_TICKET etc ...)
  • And i test this type in a switch case statement
  • Then execute the suitable method for this type

this way is a little bit borring when u have a lot of type of message. Each time i have to add a type, i have to add it in the switch case. Plus, it take more machine operations when you have hundred or thousands type of message in your protocol (due to the switch case).

Thanks.

1 answer

  • answered 2018-01-14 11:31 the4thamigo_uk

    You could use a loop over a set of handler classes (i.e. one for each type of message supported). This is essentially the composite pattern. The Component and each Composite then become independently testable. Once written Component need never change again and the support for a new message becomes isolated to a single new class (or perhaps lambda or function pointer depending on language). Also you can add/remove/reorder Composites at runtime to the Component, if that was something you wanted from your design (alternatively if you wanted to prevent this, depending on your language you could use variadic templates). Also you could look at Chain of Responsibility.

    However, if you thought that adding a case to a switch is a bit laborious, I suspect that writing a new class would be too.

    P.S. I don't see a good way of avoiding steps 1 and 2.