Java Reference
In-Depth Information
// ignore
}
}
}
The next step is optional but highly recommended. Set a timeout on the connection
using the
setSoTimeout()
method. Timeouts are measured in milliseconds, so this
statement sets the socket to time out after 15 seconds of nonresponsiveness:
socket
.
setSoTimeout
(
15000
);
Although a socket should throw a
ConnectException
pretty quickly if the server rejects
the connection, or a
NoRouteToHostException
if the routers can't figure out how to
send your packets to the server, neither of these help you with the case where a misbe‐
having server accepts the connection and then stops talking to you without actively
closing the connection. Setting a timeout on the socket means that each read from or
write to the socket will take at most a certain number of milliseconds. If a server hangs
while you're connected to it, you will be notified with a
SocketTimeoutException
. Ex‐
actly how long a timeout to set depends on the needs of your application and how
responsive you expect the server to be. Fifteen seconds is a long time for a local intranet
server to respond, but it's rather short for an overloaded public server like
time.nist.gov
.
Once you've opened the socket and set its timeout, call
getInputStream()
to return an
InputStream
you can use to read bytes from the socket. In general, a server can send
any bytes at all; but in this specific case, the protocol specifies that those bytes must be
ASCII:
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
);
Here I've stored the bytes in a
StringBuilder
. You can, of course, use any data structure
that fits your problem to hold the data that comes off the network.
Example 8-1
puts this all together in a program that also allows you to choose a different
daytime server.
Example 8-1. A daytime protocol client
import
java.net.*
;
import
java.io.*
;
public
class
DaytimeClient
{
public
static
void
main
(
String
[]
args
)
{