Friday 15 June 2012

c# - Alternative to Switch-Case Packet Handling -



c# - Alternative to Switch-Case Packet Handling -

i've been toying around network sockets, of issues coming windows forms, i've looked lot of programs private server emulators, , become dissatisfied packet handling.

each message formatted, in json, so:

{ "id":201, "message":"hello, world.", "user":"system", "color":"lawngreen" }

"id" constant in packets, , identify function of packet. packets of same id, henceforth known header, have same keys, not same values (duh, says someone).

i deserialize json dynamic , perform switch case on header of packet, so:

switch((int)jsonpacket.id) { case 201: ... }

given small-scale chat application won't begin seek , implement of irc's functions, should still concerned , dissatisfied implementation? little games/testbench servers utilize same method, don't want limiting myself in terms of functionality , performance, or if becomes nuisance.

any thoughts help.

using switch produces rather efficient code, not limit in terms of performance. rather clean code, in sense readers basic understanding of language able figure out going on.

another mutual alternative switches associative container of delegates. can create this:

private static readonly idictionary<int,action<object>> processor = new dictionary<int,action<object>> { { 201, process201 } , { 205, process205 } }; ... static void process201(object message) { // } static void process205(object message) { // else }

now can utilize array this:

processor[jsonpacket.id](jsonpacket);

this phone call appropriate method based on id packet. can create action<t> take more specific type instead of object, or pass different set of parameters altogether if decide more info packet before dispatching action handler.

c# json sockets switch-statement packet

No comments:

Post a Comment