Java Reference
In-Depth Information
the network subsystem for transmission. If the network subsystem cannot handle the message
for some reason, the packet is silently dropped (but this is rare).
The next three sections deal with some of the subtleties of sending and receiving with
TCP's byte-stream service. Then, Section 5.4 considers the connection establishment and ter-
mination of the TCP protocol. Finally, Section 5.5 discusses the process of matching incoming
packets to sockets and the rules about binding to port numbers.
5.1
Buffering and TCP
As a programmer, the most important thing to remember when using a TCP socket is this:
You cannot assume any correspondence between writes to the output stream at one end
of the connection and reads from the input stream at the other end.
In particular, data passed in a single invocation of the output stream's write() method at
the sender can be spread across multiple invocations of the input stream's read() method at
the other end; and a single read() may return data passed in multiple write() s. To see this,
consider a program that does the following:
byte[] buffer0 = new byte[1000];
byte[] buffer1 = new byte[2000];
byte[] buffer2 = new byte[5000];
.
Socket s = new Socket(destAddr, destPort);
OutputStream out = s.getOutputStream();
.
out.write(buffer0);
.
out.write(buffer1);
.
out.write(buffer2);
.
s.close();
where the ellipses represent code that sets up the data in the buffers but contains no other
calls to out.write() . Throughout this discussion, “in” refers to the InputStream of the receiver's
Socket , and “out” refers to the OutputStream of the sender's Socket .
This TCP connection transfers 8000 bytes to the receiver. The way these 8000 bytes are
grouped for delivery at the receiving end of the connection depends on the timing between
the out.write() s and in.read() s at the two ends of the connection—as well as the size of the
buffers provided to the in.read() calls.
Search WWH ::




Custom Search