| Email article link |
| Java Recipe of the Day
The following recipe is from The Java Cookbook, by Ian Darwin. All links in this recipe point to the online version of the book on the Safari Bookshelf. Buy it now, or read it online on the Safari Bookshelf. |
16.1. Contacting a Server
. 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.
Example 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 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.
View the past week's recipes: Today | Yesterday | 3 days ago | 4 days ago | 5 days ago | 6 days ago | A week ago
