O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Contacting a Server on the Applet Host

Problem

You want an applet to contact a socket-based server on the host from which it was loaded.

Solution

Use the method getCodeBase( ) to retrieve a URL for the applet host, and call the URL’s getHost( ). Use this to construct a client socket.

Discussion

For very good security reasons, applets are not permitted network access to servers on hosts other than the one from which the applet was loaded.

To reach a server on the download host, call the applet method getCodeBase( ), which yields a URL for the applet host. Call this URL’s getHost( ) method to get the hostname. Finally, use the hostname to open a client socket (see Section 15.2). For example:

URL u = getCodeBase(  ); 
String host = u.getHost(  ); 
Socket s = new Socket(host , MY_SERVER_PORT);

Of course, in real code you wouldn’t create all those temporary variables:

Socket s = new Socket(getCodeBase().getHost(  ), MY_SERVER_PORT);

And, of course, you will need error handling. Example 17-2 shows an applet that constructs a sort of login dialog and passes the results to a socket-based server on the applet host, using exactly this technique. Figure 17-1 shows the screen display.

Example 17-2. SocketApplet.java

/** Initialize the GUI nicely. */ public void init( ) { Label aLabel; setLayout(new GridBagLayout( )); int LOGO_COL = 1; int LABEL_COL = 2; int TEXT_COL = 3; int BUTTON_COL = 1; GridBagConstraints gbc = new GridBagConstraints( ); gbc.weightx = 100.0; gbc.weighty = 100.0; gbc.gridx = LABEL_COL; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required