Contacting a Server


You need to contact a server using TCP/IP.


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


There isn’t much to this in Java, in fact. When creating a socket, you pass in the hostname and the port number. The 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 15.2 sets up a Java network client, using IOException to catch errors.

Example 15-2. (simple client connection)


 * A simple demonstration of setting up a Java network client.
public class Connect {
    public static void main(String[] argv) {
        String server_name = "localhost";

        try {
            Socket sock = new Socket(server_name, 80);

            /* Finally, we can read and write on the socket. */
            System.out.println(" *** Connected to " + server_name  + " ***");

            /* . do the I/O here .. */

            sock.close(  );

        } catch ( e) {
            System.err.println("error connecting to " + 
                server_name + ": " + e);


See Also

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

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.