LJ Archive

Java Networking API

Java is a good general purpose language. It may be best known for Web Applets, but as the article shows, it has a full GUI component and can be used for any sort of application. It has also become popular lately as a server-side language, as much due to its simplification of C++'s Object-Oriented Programming model as to its portability. As a single example, Java's networking API (java.net) totally hides the difference between standard UNIX sockets and the asynchronous sockets used on Microsoft operating systems. Further, the code needed to construct, open and read from a client-side socket minus the error checking is:

Socket s = new Socket("myhost", 1234);
// DataInputStream ins = new DataInputStream(s.getInputStream());
// BufferedReader is preferable to DataInputStream<\n>
// as of JDK1.1
BufferedReader ins = new BufferedReader(
   new InputStreamReader(s.getInputStream()));
String s;
while ((s = ins.readLine()) != null) {
   // do something with this line of input
}
Similarly, a server-side socket can be created easily, bypassing the minutiae of creating a sockaddr_in, casting it and binding it:
ServerSocket ss = new ServerSocket(1234);
Socket ios;
while (s = ss.accept()) {
   // do I/O on s, which is connected to a<\n>
   // client
}
To read from a web server, an even greater saving of code is possible:
URL darwin = new URL("http://www.darwinsys.com/java");
InputStream ins = darwin.openStream();
// can then construct a DataInputStream or<\n>
// BufferedReader as above
This code (again, the error handling is omitted) parses the URL, connects to the web server for the URL and lets you get a Stream connection for reading its contents as text. More detailed calls are available to deal with non-textual URLs.

Java provides similar economy of API in many other areas. For details, refer to the my Java web site at http://www.darwinsys.com/java/ or to Sun's Java web site at http://java.sun.com/.

LJ Archive