norq
norq

Reputation: 1434

Design suggestions for client receiving messages over network

I'm programming a client that receives a set of different messages from a server via TCP. I have created a simple test class that is able to connect to the server and receive messages in form of NSData chunks. But now I'm stuck at how to proceed from here and need some design suggestions.

One idea I have is to create a protocol that for each message, notifies the delegate with the type of message received and an object containing the message:

Protocol

-(void)didReceiveLifesign:(LifesignMessage*)message;
-(void)didReceiveLocation:(LocationMessage*)message;
...

Parser

-(void)didReceiveData:(NSData*)data {
    int type = getType(data);
    switch(type) {
        case 0: [self.delegate didReceiveLifesign:parseLifesign(data); break;
        case 1: [self.delegate didReceiveLocation:parseLocation(data); break;
        ...
    }
}

But as the amount of messages grow I find this solution messy. Is there a prettier way of doing this?

Upvotes: 1

Views: 81

Answers (1)

Darius X.
Darius X.

Reputation: 2937

Each time you add a new type of message to the system, you will be adding new code to handle that particular type. You cannot get away from that. So, the place you can really abstract-out right now is the dispatching: the switch statement, in your case.

If very few new message-types will be added in the future, the simplest approach may be the one you have already taken: simply add a new "case" each time.

An alternate approach is to allow other code to register as a "listener"/"callback". That makes the dispatching generic. The logic becomes:

  • Find the message type
  • Dispatch to all registered callbacks/listeners

The new "problem" would be: you will now need to register each listener at some point. This would be sdone during some type of initialization. it may not be worth it if your message dispatcher is basically part of the overall app, and is not to be used elsewhere.

Upvotes: 1

Related Questions