Within the browser all applets run on a single Java Virtual Machine. Applets can call each others' methods. They can find out about each other's existance through the getApplet or getApplets methods. The (default) security manager forbids (finding out about or) calling methods from applets in different Web-pages.
Below is an example of two communicating applets:
import java.applet.*; import java.awt.Graphics; import java.lang.Thread; public class ClientServer extends Applet { String s1, s2; public synchronized void init() { try { Thread.sleep(1000); // wait for client and server to exist } catch (InterruptedException e) { ; } ClientServer Server = (ClientServer)getAppletContext().getApplet("Server"); if (this == Server) { s1 = "This is the Server"; ClientServer Client = (ClientServer)getAppletContext().getApplet("Client"); if (Client == null) s2 = "Server: cannot find client."; else { String Msg = getParameter("message"); Client.Message(Msg); } } else { s1 = "This is the Client"; } } void Message(String msg) { s2 = msg; } public void paint(Graphics g) { if (s1 != null) g.drawString(s1, 20, 20); if (s2 != null) g.drawString(s2, 20, 40); } }
The HTML code for this example is:
<APPLET code="ClientServer.class" codebase="/2R350/applets" width=200 height=50 name="Server"> <PARAM NAME="message" VALUE="Message from Server"> <IMG src="/2R350/images/appcomm.gif"> </APPLET> <APPLET code="ClientServer.class" codebase="/2R350/applets" width=200 height=50 name="Client"> </APPLET>