title: How to define a communication protocol?
body: <p>I'm new to networking concepts and need an explaination of how to implement a communication protocol for sending different types of messages. I'm currently working on a Cocoa app that will send video messages between iPhones. Currently I only send messages of type 3. Here's the app flow I need to implement:</p>
  
  <ol>
  <li><p>Browsing for available iPhones on the network (using Bonjour) </p></li>
  <li><p>When an iPhone client is found, send NSData "request contact info"  (<em>MessageType1</em>)</p>
  
  <p>iPhone client will send back an NSData instance with contact info (<em>MessageType2</em>)</p></li>
  <li><p>Init a new message with recorded video, send to selected contact (<em>MessageType3</em>)</p></li>
  </ol>
  
  <p>When the different types of message are received, they will need to be handled differently. I guess one way to solve it is to add a header to the message that identify the message type and extract this on the receiver's side, then handle like this:</p>
  
  <pre><code>if (messageType == 1)  // MessageType1
      [self sendMyContactInfo:(Contact *)ownInfo];
  
  if (messageType == 2)  // MessageType2
      [self updateViewWithContactInfo:(Contact *)contactInfo];
  
  if (messageType == 3)  // MessageType3
      [self sendMessageToSelectedContact:(Message *)message]
  </code></pre>
  
  <p>For creating a message for MessageType3, I'll do this: </p>
  
  <pre><code>/* Not currently implemented */
  NSMutableData *data = [[NSMutableData alloc] init];
  int messageType = 3;
  [data appendBytes:messageType]
  
  /* Already Implemented */
  NSData *encodedMessage = [NSKeyedArchiver archivedDataWithRootObject:message];
  [data appendData:encodedMessage];
  
  [self sendMessage:(NSData *)encodedMessage];
  </code></pre>
  
  <p>Is this a nice way of doing it? If so, should the protocol rules be defined in a more formal way, e.g. in a separate class or something? I'm looking for the best overall solution here, so don't take too much notice of my drawings if there's a better way to do it...</p>