Java Reference
In-Depth Information
chapter 3
Sending and Receiving Messages
W hen writing programs to communicate via sockets, you will generally be implementing
an application protocol of some sort. Typically you use sockets because your program needs to
provide information to, or use information provided by, another program. There is no magic:
sender and receiver must agree on how this information will be encoded, who sends what
information when, and how the communication will be terminated. In our echo example, the
application protocol is trivial: neither the client's nor the server's behavior is affected by the
contents of the bytes they exchange. Because most applications require that the behaviors of
client and server depend upon the information they exchange, application protocols are usually
more complicated.
The TCP/IP protocols transport bytes of user data without examining or modifying them.
This allows applications great flexibility in how they encode their information for transmission.
For various reasons, most application protocols are defined in terms of discrete messages
made up of sequences of fields . Each field contains a specific piece of information encoded
as a sequence of bits. The application protocol specifies exactly how these sequences of bits
are to be formatted by the sender and interpreted, or parsed , by the receiver so that the latter
can extract the meaning of each field. About the only constraint imposed by TCP/IP is that
information must be sent and received in chunks whose length in bits is a multiple of eight. So
from now on we consider messages to be sequences of bytes . Given this, it may be helpful to
think of a transmitted message as a sequence of numbers, each between 0 and 255, inclusive
(that being the range of binary values that can be encoded in 8 bits—1 byte).
As a concrete example for this chapter, let's consider the problem of transferring price
quote information between vendors and buyers. A simple quote for some quantity of a
particular item might include the following information:
Item number: A large integer identifying the item
Item description: A text string describing the item
Unit price: The cost per item in cents
Quantity: The number of units offered at that price
37
 
Search WWH ::




Custom Search