Java Reference
In-Depth Information
String
hostname
=
args
.
length
>
0
?
args
[
0
]
:
"time.nist.gov"
;
Socket
socket
=
null
;
try
{
socket
=
new
Socket
(
hostname
,
13
);
socket
.
setSoTimeout
(
15000
);
InputStream
in
=
socket
.
getInputStream
();
StringBuilder
time
=
new
StringBuilder
();
InputStreamReader
reader
=
new
InputStreamReader
(
in
,
"ASCII"
);
for
(
int
c
=
reader
.
read
();
c
!=
-
1
;
c
=
reader
.
read
())
{
time
.
append
((
char
)
c
);
}
System
.
out
.
println
(
time
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
finally
{
if
(
socket
!=
null
)
{
try
{
socket
.
close
();
}
catch
(
IOException
ex
)
{
// ignore
}
}
}
}
}
Typical output is much the same as if you connected with Telnet:
$
java DaytimeClient
56375 13-03-24 15:05:42 50 0 0 843.6 UTC(NIST) *
As far as network-specific code goes, that's pretty much it. In most network programs
like this, the real effort is in speaking the protocol and comprehending the data formats.
For instance, rather than simply printing out the text the server sends you, you might
want to parse it into a
java.util.Date
object instead.
Example 8-2
shows you how to
do this. For variety, I also wrote this example taking advantage of Java 7's
AutoCloseable
and try-with-resources.
Example 8-2. Construct a Date by talking to time.nist.gov
import
java.net.*
;
import
java.text.*
;
import
java.util.Date
;
import
java.io.*
;
public
class
Daytime
{
public
Date
getDateFromNetwork
()
throws
IOException
,
ParseException
{
try
(
Socket
socket
=
new
Socket
(
"time.nist.gov"
,
13
))
{
socket
.
setSoTimeout
(
15000
);
InputStream
in
=
socket
.
getInputStream
();
StringBuilder
time
=
new
StringBuilder
();