Java Reference
In-Depth Information
InputStreamReader reader = new InputStreamReader ( in , "ASCII" );
for ( int c = reader . read (); c != - 1 ; c = reader . read ()) {
time . append (( char ) c );
}
return parseDate ( time . toString ());
}
}
static Date parseDate ( String s ) throws ParseException {
String [] pieces = s . split ( " " );
String dateTime = pieces [ 1 ] + " " + pieces [ 2 ] + " UTC" ;
DateFormat format = new SimpleDateFormat ( "yy-MM-dd hh:mm:ss z" );
return format . parse ( dateTime );
}
}
Notice, however, this class doesn't actually do anything with the network that
Example 8-1 didn't do. It just added a bunch of code to turn strings into dates.
When reading data from the network, it's important to keep in mind that not all pro‐
tocols use ASCII or even text. For example, the time protocol specified in RFC 868
specifies that the time be sent as the number of seconds since midnight, January 1, 1900,
Greenwich Mean Time. However, this is not sent as an ASCII string like 2,524,521,600
or -1297728000. Rather, it is sent as a 32-bit, unsigned, big-endian binary number.
The RFC never actually comes out and says that this is the format used.
It specifies 32 bits and assumes you know that all network protocols
use big-endian numbers. The fact that the number is unsigned can be
determined only by calculating the wraparound date for signed and
unsigned integers and comparing it to the date given in the specifica‐
tion (2036). To make matters worse, the specification gives an exam‐
ple of a negative time that can't actually be sent by time servers that
follow the protocol. Time is a relatively old protocol, standardized in
the early 1980s before the IETF was as careful about such issues as it
is today. Nonetheless, if you find yourself implementing a not partic‐
ularly well-specified protocol, you may have to do a significant amount
of testing against existing implementations to figure out what you need
to do. In the worst case, different implementations may behave differ‐
ently.
Because the time protocol doesn't send back text, you can't easily use Telnet to test such
a service, and your program can't read the server response with a Reader or any sort of
readLine() method. A Java program that connects to time servers must read the raw
bytes and interpret them appropriately. In this example, that job is complicated by Java's
lack of a 32-bit unsigned integer type. Consequently, you have to read the bytes one at
a time and manually convert them into a long using the bitwise operators << and | .
Search WWH ::




Custom Search