Java Reference
In-Depth Information
See Also
See NetworkInterface in Finding Network Interfaces , which lets you find out more about
the networking of the machine you are running on.
There is not yet a way to look up services—i.e., to find out that the HTTP service is on port
80. Full implementations of TCP/IP have always included an additional set of resolvers; in
C, the call getservbyname("http" , " tcp"); would look up the given service [ 39 ] and return
a servent (service entry) structure whose s_port member would contain the value 80. The
numbers of established services do not change, but when services are new or installed in
nonroutine ways, it is convenient to be able to change the service number for all programs on
a machine or network (regardless of programming language) just by changing the services
definitions. Java should provide this capability in a future release.
Handling Network Errors
Problem
You want more detailed reporting than just IOException if something goes wrong.
Solution
Catch a greater variety of exception classes. SocketException has several subclasses; the
most notable are ConnectException and NoRouteToHostException . The names are self-
explanatory: the first means that the connection was refused by the machine at the other end
(the server machine), and the second completely explains the failure. Example 13-3 is an ex-
cerpt from the Connect program, enhanced to handle these conditions.
Example 13-3. ConnectFriendly.java
public
public class
class ConnectFriendly
ConnectFriendly {
public
public static
void main ( String [] argv ) {
String server_name = argv . length == 1 ? argv [ 0 ] : "localhost" ;
int
static void
int tcp_port = 80 ;
try
try ( Socket sock = new
new Socket ( server_name , tcp_port )) {
/* If we get here, we can read and write on the socket. */
System . out . println ( " *** Connected to " + server_name + " ***" );
/* Do some I/O here... */
 
Search WWH ::




Custom Search