I have a server application and a client applet and I want to know what the best way to communicate between them is. I have thought of two possibilities. The first one is a text-based protocol where messages are sent by using DataOutputStream.writeUTF(String str). In the other a code (byte) describing the message is sent first, and then data in various formats (byte, long, String). Less data (in bytes) would be needed to sent but the problem is that if the receiver didn't read the right number of bytes, the next messages would be screwed up. Which method would you recommend or is there an article I should read?
Edit: It is a multiplayer game. If a player's status changes (which happens often), the new status needs to be sent to other players. [ March 28, 2006: Message edited by: Matti Poro ]
Another option you should strongly consider is the use of UDP instead of TCP -- i.e., DatagramSockets instead of Socket/ServerSocket. Real-time games rarely use connnection-oriented reliable communication (TCP) because a single bad client connection will slow down the game for all players. Connectionless, unreliable UDP ensures that a bad connection will affect a single client only.
The Java Tutorial has an example of a protocol in the client server pair tutorial. You have to encapsulate your data in a package so you don't have the problems in your second example. The above tutorial uses text lines to package the data. It may be easier to use object serialization rather than a low-level protocol. There's some overhead to the serialization process, but it can greatly simplify the translation and processing of data. (i.e. no text parsing, you can use polymorphism to route different messages rather than huge if/then/else blocks). Of course, serialization has its own pitfalls. Serializing an object serializes all its references, so if you have a Game object that has references to every player, npc, map and so on, don't expect to be transmitting it across the wire.