Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata