16.1. Contacting a Server

. Problem

You need to contact a server using TCP/IP.

. Solution

Just create a Socket, passing the hostname and port number into the constructor.

. Discussion

There isn't much to this in Java, in fact. When creating a socket, you pass in the hostname and the port number. The java.net.Socket constructor does the gethostbyname( ) and the socket( ) system call, sets up the server's sockaddr_in structure, and executes the connect( ) call. All you have to do is catch the errors, which are subclassed from the familiar IOException . Example 16-2 sets up a Java network client, using IOException to catch errors.

. See Also

Java supports other ways of using network applications. You can also open a URL and read from it (see Recipe 18.7). You can write code so that it will run from a URL, when opened in a web browser, or from an application.