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 15.2 sets up a Java network client, using IOException to catch errors.

Example 15-2. Connect.java (simple client connection)

import java.net.*;

/*
 * 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 (java.io.IOException e) {
            System.err.println("error connecting to " + 
                server_name + ": " + e);
            return;
        }

    }
}

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.