Java Reference
In-Depth Information
Call
close()/shutdownOutput()
Returns immediately
Established
Closing
Half closed
Time-Wait
Start
close
handshake
Close
handshake
complete
s
Close
handshake
initiated by
remote
completes
Local port
P
A.B.C.D
Local port
P
A.B.C.D
Local port
P
A.B.C.D
Local port
P
A.B.C.D
Local IP
Local IP
Local IP
Local IP
Remote port
Remote IP
Q
W.X.Y.Z
Remote port
Remote IP
Q
W.X.Y.Z
Remote port
Remote IP
Q
W.X.Y.Z
Remote port
Remote IP
Q
W.X.Y.Z
Figure 5.10:
Closing a TCP connection first.
compression example of Section 4.5. It works like this: the application indicates that it is
finished sending data on a connected socket by calling
close()
or by calling
shutdownOutput()
.
At that point, the underlying TCP implementation first transmits any data remaining in
SendQ
(subject to available space in
RecvQ
at the other end), and then sends a closing TCP handshake
message to the other end. This closing handshake message can be thought of as an end-of-
transmission marker: it tells the receiving TCP that no more bytes will be placed in
RecvQ
.
(Note that the closing handshake message itself is
not
passed to the receiving application,
but that its position in the byte stream is indicated by
read()
returning
1.) The closing TCP
waits for an acknowledgment of its closing handshake message, which indicates that all data
sent on the connection made it safely to
RecvQ
. Once that acknowledgment is received, the
connection is “Half closed.” It is not
completely
closed until a symmetric handshake happens
in the other direction—that is, until
both
ends have indicated that they have no more data to
send.
−
The closing event sequence in TCP can happen in two ways: either one application calls
close()
(or
shutdownOutput()
) and completes its closing handshake before the other calls
close()
, or both call
close()
simultaneously, so that their closing handshake messages cross
in the network. Figure 5.10 shows the sequence of events in the implementation when the
application invokes
close()
before
the other end closes. The closing handshake message is
sent, the state of the socket structure is set to “Closing”, and the call returns. After this
point, further reads and writes on the
Socket
are disallowed (they throw an exception). When
the acknowledgment for the close handshake is received, the state changes to “Half closed”,
where it remains until the other end's close handshake message is received. Note that if the
remote endpoint goes away while the connection is in this state, the local underlying structure
will stay around indefinitely. When the other end's close handshake message arrives, an
acknowledgment is sent and the state is changed to “Time-Wait”. Although the corresponding
Socket
instance in the application program may have long since vanished, the associated
underlying structure continues to exist in the implementation for a minute or more; the reasons
for this are discussed on page 107.
Search WWH ::
Custom Search