Desh Banks
Desh Banks

Reputation: 403

Java Chat system protocol design, how to determine message type?

I have a chat program implemented in Java. The client can send lots of different types of information to the server (i.e, Joins the server and sends username, password; requests a private chat with another user on the server, disconnects from the server, etc).

I'm looking for the correct way to have the server/client differentiate between 'text' messages that are just meant to be chat text messages sent from one client to the others, and 'command' messages (disconnect, request private chat, request file transfer, etc) that are meant for the server or the client.

I see two options:

  1. Use serialized objects, and determine what they are on the receiving end by doing an 'instanceof'
  2. Send the data as a byte array, reserving the first N bytes of the array to specify the 'type' of the incoming data.

What is the 'correct' way to do this? How to real protocols (oscar, irc) handle this situation?

I've googled around on this topic and only found examples/discussions centering on simple java chat applications. None that go into detail about protocol design (which I ultimately intend to practice).

Thanks to any help...

Upvotes: 2

Views: 1384

Answers (2)

Odysseus
Odysseus

Reputation: 1092

Second approach is much better, because serialization is a complex mechanism, that can be easily used in a wrong way (for example you may bind yourself to internal content of a concrete serialized class). Plus your protocol will be bound to JVM mechanism. Using some "protocol header" for message differentiation is a common way in network protocols (FTP, HTTP, etc). It is even better when it is in a text form (people will be able to read it).

Upvotes: 2

aioobe
aioobe

Reputation: 420951

You typically have a little message header identifying the type of content in all messages, including standard text/chat messages.

Either of your two suggestions are fine. (In your second approach, you probably want to reserve some bytes for the length of the array as well.)

Upvotes: 2

Related Questions