84 Chapter 3: Sending and Receiving Messages
■
System.Runtime.Serialization.Formatters name spaces contain classes that support
writing a C# class instance to an XML (eXtensible Markup Language) file, binary format,
or SOAP (Simple Object Access Protocol) message suitable for sending over a network
connection. Once at the remote host, the file can be deserialized into a instance of that
object. Similarly, the System.Runtime.Remoting name space allows the ability to create a
remote proxy object that a client can use to invoke methods on a server’s object. It might
seem that having these interfaces available would eliminate the need for what we have
described in this chapter, and that is true to some extent. However, it is not always the
case for several reasons.
First, the encoded forms produced by Serializable may not be very efficient. They
may include information that is meaningless outside the context of the Common Language
Runtime (CLR), and may also incur overhead to provide flexibility that may not be needed.
Second, Serializable and Remoting cannot be used when a different wire format has
already been specified—for example, by a standardized protocol. And finally, custom-
designed classes have to provide their own implementations of the serialization interfaces
anyway.
A basic tenet of good protocol design is that the protocol should constrain the imple-
mentor as little as possible and should minimize assumptions about the platform on
which the protocol will be implemented. We therefore avoid the use of Serializable and
Remoting in this book, and instead use more direct encoding and decoding methods.
3.6 Exercises
1. What happens if the Encoder uses a different encoding than the Decoder?
2. Rewrite the binary encoder so that the Item Description is terminated by “\r\n”
instead of being length encoded. Use Send/RecvTcp to test this new encoding.
3. The nextToken() method of Framer assumes that either the delimiter or an end-of-
stream (EoS) terminates a token; however, finding the EoS may be an error in some
protocols. Rewrite nextToken() to include a second Boolean parameter. If the param-
eter value is true, then the EoS terminates a token without error; otherwise, the EoS
generates an error.
4. Using the code provided on the website of the Java version of this book ([25],
www.mkp.com/practical/javasockets), run a C# receiver and a Java sender, and
vice versa. Verify that the contents are sent and received properly. Try removing
the NetworkToHostOrdering() and HostToNetworkOrdering() method calls and
rerunning the experiment.