Previous | Next | Trail Map | Writing Applets | Communicating with Other Programs


Working with a Server-Side Application

Applets, like other Java programs, can use the API defined in the java.net package to communicate across the network. The only difference is that, for security reasons, the only host an applet can communicate with is the host it was delivered from.

It's easy to find out which host an applet came from. Just use the Applet getCodeBase() method and the java.net.URL getHost() method, like this:

String host = getCodeBase().getHost();
If you specify a host name even slightly different from the one the user specified for the applet, all existing security managers forbid the communication, even if the two names specify the same host. Using the above code (instead of a hard-coded host name) ensures that your applet will use the one correct host name.

Once you have the right host name, you can use all the networking code, as documented in the Custom Networking and Security(in the Networking trail)trail. The Writing a Datagram Client and Server(in the Networking trail)page of that trail contains example code for two applications, a client and a server. Here is an applet version of the client: QuoteClientApplet.java. It's been changed not only to communicate with the host the applet came from, but also to have a graphical UI, and to have a loop so that it can get as many quotes as you like. You can run the applet by including it in a page, with the following HTML code:

<applet code=QuoteClientApplet.class width=500 height=100>
</applet>
Before you can get quotes in the applet, you need to run the server on the host that the applet came from. You then need to note the port that the server is listening on. After you enter this number into the applet, it'll hook up with the server, and you'll be able to get one-line quotations. Below are detailed instructions.
  1. Compile QuoteServer.java and QuoteServerThread.java. Here's a text file (one-liners) that should be in the same directory as the resulting class files.
  2. On the computer that serves the applet class file (through HTTP), invoke the interpreter on the QuoteServer class file.
  3. Record the port number that the quote server prints out.
  4. Enter this number into the applet's text field.
  5. Press the Send button to request a quote from the server. You should see a quote appear in the text area.
Here's a picture of the server in action:

Here's a picture of the applet in action:


Previous | Next | Trail Map | Writing Applets | Communicating with Other Programs