Java Reference
In-Depth Information
• The string
UTC(NIST)
is a constant, and the
OTM
is almost a constant (an asterisk
unless something really weird has happened).
These details are all NIST specific. They are not part of the daytime standard. Although
they do offer a lot of data, if you have a real programmatic need to sync with a network
I'm not sure how long this example is going to work as shown here.
These servers are overloaded, and I did have intermittent problems
connecting while writing this chapter. In early 2013,
NIST an‐
also strongly encouraged to upgrade to the network time protocol,
which provides greater accuracy and requires less network band‐
width. The NIST time client (nistime-32bit.exe) supports both proto‐
cols. We expect to replace the tcp version of this protocol with a udp-
based version near the end of 2013.” I'll show you how to access this
service over UDP in
Chapter 11
.
Now let's see how to retrieve this same data programmatically using sockets. First, open
a socket to
time.nist.gov
on port 13:
Socket
socket
=
new
Socket
(
"time.nist.gov"
,
13
);
This doesn't just create the object. It actually makes the connection across the network.
If the connection times out or fails because the server isn't listening on port 13, then the
constructor throws an
IOException
, so you'll usually wrap this in a
try
block. In Java
7,
Socket
implements
Autocloseable
so you can use try-with-resources:
try
(
Socket
socket
=
new
Socket
(
"time.nist.gov"
,
13
))
{
// read from the socket...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
"Could not connect to time.nist.gov"
);
}
In Java 6 and earlier, you'll want to explicitly close the socket in a
finally
block to
release resources the socket holds:
Socket
socket
=
null
;
try
{
socket
=
new
Socket
(
hostname
,
13
);
// read from the socket...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
finally
{
if
(
socket
!=
null
)
{
try
{
socket
.
close
();
}
catch
(
IOException
ex
)
{