![]() ![]() ![]() ![]() |
Communicating with Other Programs |
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.URLgetHost()
method, like this: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.String host = getCodeBase().getHost();Once you have the right host name, you can use all the networking code, as documented in the Custom Networking and Security
trail. The Writing a Datagram Client and Server
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:
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.<applet code=QuoteClientApplet.class width=500 height=100> </applet>Here's a picture of the server in action:
- 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.
- On the computer that serves the applet class file (through HTTP), invoke the interpreter on the QuoteServer class file.
- Record the port number that the quote server prints out.
- Enter this number into the applet's text field.
- 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 applet in action:
![]()
![]() ![]() ![]() ![]() |
Communicating with Other Programs |