Java Reference
In-Depth Information
for implementations of the TCP/IP protocols.) For most applications, the designers did a good
job; however, it is seldom the case that “one size fits all” really fits all. We have already seen
an example in our UDP echo client. By default, the receive() method of DatagramSocket blocks
indefinitely waiting on a datagram. In our example, we change that behavior by specifying a
timeout for receives on the UDP socket using setSoTimeout() . In socket parlance, each type
of behavior we can change is called a socket option . In Java, the socket type (e.g., Socket ,
ServerSocket , DatagramSocket , and MulticastSocket ) determines the applicable socket options,
which are typically queried and controlled using accessor methods like getSoTimeout() and
setSoTimeout() . Unfortunately, the Java API allows access to only a subset of the options in
the underlying sockets API. This is at least partly because options tend to vary in availability
from platform to platform, and Java is all about portability. However, as the versions wear
on, access to more and more socket options is being added in Java. Check the latest ocial
documentation for the various socket types to see the available options.
4.5
Closing Connections
You've probably never given much thought to who closes a connection. In phone conversations,
either side can start the process of terminating the call. It typically goes something like this:
“Well, I guess I'd better go.”
“OK. Bye.”
“Bye.”
Network protocols, on the other hand, are typically very specific about who “closes” first.
In the echo protocol, Figure 4.1(a), the server dutifully echoes everything the client sends. When
the client is finished, it calls close() . After the server has received and echoed all of the data
sent before the client's call to close() , its read operation returns a
1, indicating that the client
is finished. The server then calls close() on its socket. The close is a critical part of the protocol
because without it the server doesn't know when the client is finished sending characters to
echo. In HTTP, Figure 4.1(b), it's the server that initiates the connection close. Here, the client
sends a request (“
get
”) to the server, and the server responds by sending a header (normally
"To Be"
"Get/Guide.html …"
"To Be"
"Or Not To Be"
"Or Not To Be"
Closed
Closed
"200 OK …
<HTML> …
… </HTML>"
Closed
Closed
(a)
(b)
Figure 4.1: Echo (a) and HTTP (b) protocol termination.
Search WWH ::




Custom Search