Simple Serialized Object Protocols
Earlier in this chapter, we showed a hypothetical conversation in which a client and server exchanged some primitive data and a serialized Java object. Passing an object between two programs may not have seemed like a big deal at the time, but, in the context of Java as a portable bytecode language, it has big implications. In this section, we show how a protocol can be built using serialized Java objects.
Before we move on, it’s worth considering network protocols. Most programmers would consider working with sockets to be tedious and complex. Even though Java makes sockets much easier to use than many other languages, sockets still provide only an unstructured flow of bytes between their endpoints. If you want to do serious communications using sockets, the first thing you have to do is come up with a protocol that defines the data you are sending and receiving. The most complex part of that protocol usually involves how to marshal (package) your data for transfer over the Net and unpack it on the other side.
As we’ve seen, Java’s DataInputStream and DataOuputStream classes solve this problem for
simple data types. We can read and write numbers, Strings, and Java primitives in a standard format that can be understood on any other Java platform. To do real work, however, we need to be able to put simple types together into larger structures. Java object serialization solves this problem elegantly by allowing us to send our data in the state in ...