Java Reference
In-Depth Information
}
}
The algorithm for calculating which bytes to write when is the same as for the previous
implementation. The crucial difference is that the bytes are packed into a byte array
before being written onto the network. Also, notice that the int result of the calculation
must be cast to a byte before being stored in the array. This wasn't necessary in the
previous implementation because the single-byte write() method is declared to take
an int as an argument.
Streams can also be buffered in software, directly in the Java code as well as in the
network hardware. Typically, this is accomplished by chaining a BufferedOutput
Stream or a BufferedWriter to the underlying stream, a technique we'll explore shortly.
Consequently, if you are done writing data, it's important to flush the output stream.
For example, suppose you've written a 300-byte request to an HTTP 1.1 server that uses
HTTP Keep-Alive. You generally want to wait for a response before sending any more
data. However, if the output stream has a 1,024-byte buffer, the stream may be waiting
for more data to arrive before it sends the data out of its buffer. No more data will be
written onto the stream until the server response arrives, but the response is never going
to arrive because the request hasn't been sent yet! Figure 2-1 illustrates this catch-22.
The flush() method breaks the deadlock by forcing the buffered stream to send its data
even if the buffer isn't yet full.
Figure 2-1. Data can get lost if you don't flush your streams
It's important to flush your streams whether you think you need to or not. Depending
on how you got hold of a reference to the stream, you may or may not know whether
it's buffered. (For instance, System.out is buffered whether you want it to be or not.) If
 
Search WWH ::




Custom Search