Java Reference
In-Depth Information
It might be a good exercise to isolate the reading and writing code from this method into a
NetWriter class, possibly subclassing PrintWriter and adding the \r\n and the flushing.
Reading and Writing Binary Data
Problem
Having connected, you wish to transfer binary data.
Solution
Construct a DataInputStream or DataOutputStream from the socket's getInputStream()
or getOutputStream() .
Discussion
The simplest paradigm for reading/writing on a socket is:
DataInputStream is = new DataInputStream(sock.getInputStream());
DataOutputStream is = new DataOutputStream(sock.getOutputStream( ));
If the volume of data might be large, insert a buffered stream for efficiency. The paradigm is:
DataInputStream is = new DataInputStream(
new BufferedInputStream(sock.getInputStream( )));
DataOutputStream is = new DataOutputStream(
new BufferedOutputStream(sock.getOutputStream( )));
The program example in Example 13-6 uses another standard service that gives out the time
as a binary integer representing the number of seconds since 1900. Because the Java Date
class base is 1970, we convert the time base by subtracting the difference between 1970 and
1900. When I used this exercise in a course, most of the students wanted to add this time dif-
ference, reasoning that 1970 is later. But if you think clearly, you'll see that there are fewer
seconds between 1999 and 1970 than there are between 1999 and 1900, so subtraction gives
the correct number of seconds. And because the Date constructor needs milliseconds, we
multiply the number of seconds by 1,000.
Search WWH ::




Custom Search