Java Reference
In-Depth Information
if (key == null) {
key = “”;
} else {
key = key + “: “;
}
if (header != null) {
text.append(key + header + “\n”);
}
i++;
} while (header != null);
text.append(“\n”);
Sockets
For networking applications beyond what the
URL
and
URLConnection
classes offer (for
example, for other protocols or for more general networking applications), Java provides
the
Socket
and
ServerSocket
classes as an abstraction of standard Transmission Control
Protocol (TCP) socket programming techniques.
17
The
Socket
class provides a client-side socket interface similar to standard UNIX sock-
ets. Create a new instance of
Socket
to open a connection (where
hostName
is the host
to connect to and
portNumber
is the port number):
Socket connection = new Socket(
hostName
,
portNumber
);
After you create a socket, set its timeout value, which determines how long the applica-
tion waits for data to arrive. This is handled by calling the socket's
setSoTimeOut(
int
)
method with the number of milliseconds to wait as the only argument:
connection.setSoTimeOut(50000);
By using this method, any effort to read data from the socket represented by
connection
waits for only 50,000 milliseconds (50 seconds). If the timeout is reached, an
InterruptedIOException
is thrown, which gives you an opportunity in a
try
-
catch
block to either close the socket or try to read from it again.
If you don't set a timeout in a program that uses sockets, it might hang indefinitely wait-
ing for data.
This problem is usually avoided by putting network operations in
their own thread and running them separately from the rest of the
program, a technique used with animation on Day 7, “Exceptions,
Assertions, and Threads.”
TIP