by David Wood

Pour On The Java.  Hold The Programming.  Click Here.  Jamba.

Socket Programming in Java

This week we're going to deliver the goods, so to speak, on socket programming in Java.

Three weeks ago, we used the URLConnection class in an applet to snatch up a second copy of this column and display it as a kind of recursive example. This week we're duplicating the trick, only this time we're doing it with the Socket class to illustrate the basic, although potentially subtle, difference.

The original example follows. To sum it up, it's a loop that streams out the contents of a URLConnection into the text box.



import java.applet.Applet;
import java.awt.*;
import java.io.*;
import java.net.*;

public class sourcedisplay extends Applet
{
   URL ourhome;
   URLConnection ourlink;
   DataInputStream ourstream;

   public void init()
   {
      try
      {
         ourhome = getDocumentBase();
         ourlink = ourhome.openConnection();
      
         ourlink.connect();
         ourstream = new DataInputStream(ourlink.getInputStream());
      }
      catch (IOException ioe)
      {
         System.err.println(ioe.toString());
      }

      TextArea da = new TextArea(9,40);
      da.setEditable(false);

      try
      {
         String buffer;
         while ((buffer = ourstream.readLine()) != null)
            da.appendText(buffer+"\n");
      }
      catch (IOException ioe)
      {
         System.err.println(ioe.toString());
      }

      add(da);
      validate();
   
   }
}

Our goal is to do the same thing with a plain socket, instead of a URLConnection. Keep in mind, first of all, that a URLConnection is more or less a kind of socket. Our new applet will not be fundamentally different. There will still be a loop that reads out of a stream from the socket and writes the data into a TextArea. The changes are as follows:

That's what the URLConnection and the URL classes do for us: It extends an ordinary hostname into a URL (which, besides the name of the "target" computer, holds a number of additional things) and specializes the socket into a "Web Connection." Note that, by design, it is not just an "HTTP Connection"--the system is laid out so that, just as the designers of the web intended, any protocol supplied in the URL is used if the appropriate handler is there to support it.

Although speaking in HTTP might sound as complicated as speaking a real foreign language, it's not at all, especially for what we want to do with it now. Simply requesting the document you're reading from the iWORLD Web server requires little complexity on our part. Not to mention that HTTP is largely human readable. For those readers not initiated into the select and elite group who can speak Internet protocols at will, let us assure you that this is not uncommon, and, in fact, HTTP is following the tradition of a number of the most widely used protocols on the Net. Rather than having client-server technology communicating with inscrutable binary formatted protocols, the architects of the Internet have (perhaps sensibly) opted for exchanges easily understandable to humans. You'll see what we mean in a minute.

Basically, we're going to call up the Web server at this host (at port 80) and send it a string requesting the specific document we want, like follows:

GET /document/in/question.html HTTP/1.0

HTTP dictates we identify the type of request we are making of the server ("GET") and the version of the protocol we are using ("HTTP/1.0"). Then we send two new lines, and the server will immediately respond with the document. It's almost that simple. Actually, the Web server will preface the information it's about to return to us with a header, carrying information about itself, the document, instructions for a Web browser, and so forth. The header is separated from the document itself by a single blank line.

In other words: Once we connect, we send the request string, two new lines, and then start reading what the server sends back. Reading a blank line is our signal that whatever document the server is sending us is starting to come. We are ignoring the header for the moment--to go too deeply into those vagaries of HTTP is beyond the scope of this column.

Thus:



Here's the source code. Go ahead and check it out. Notice that in this second example, we use the getDocumentBase() method on our applet to determine which host to connect to and which document to request--simply by asking the URL this method returns which host and file it contains.

Our conversation over this socket with the network involves two streams and is now apparently two-way: We send the request on one and then read the returned data on the other. But remember this conversation has always been two-way--it's just that the first time around it was moderated by the URLConnection object. Automated for us, so to speak.

In the future we'll have some additional examples to show for basic networking. As for this time around, to sum up, pay attention to the real difference between the Web-related class and the basic networking class (URLConnection vs. Socket). It is illustrative of several important facts: about the networking protocols in play and about the way a good networking system is organized--from general to specific.

Past installments of Java Jolt

http://www.internet.com/