Applet Client
If at some point you provide a service from your host computer (the one supplying an applet), you might want to include a simple client applet on your home page so that people can try out the service over the Web. Applet Clients combine graphical user interfaces, sockets to establish a connection from client to server, streams which represent the input and output channels, and threads to wait for data from the server. Keep in mind that Java applets usually cannot read or write from the disk on the machine where the browser is running. Java applets also cannot connect to systems other than the one on which they were originally stored.
Here's an Applet Client example:
import java.applet.*; import java.awt.*; import java.io.*; import java.net.*; import java.awt.event.*; public class AppletClient extends Applet implements ActionListener { public static final int PORT = 6000; Socket s; BufferedReader in; PrintStream out; TextField inputfield; TextArea outputarea; StreamListener listener; public void init() { try { s=new Socket("127.0.0.1",PORT); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintStream(s.getOutputStream()); inputfield = new TextField(); outputarea = new TextArea(80,30); outputarea.setEditable(false); this.setLayout(new BorderLayout()); this.add("North",inputfield); this.add("Center",outputarea); inputfield.addActionListener(this); listener = new StreamListener(in,outputarea); outputarea.setText("Connected to " + s.getInetAddress().getHostName() + ";" + s.getPort()+"\n"); } catch(IOException e) {this.showStatus(e.toString());} } public void actionPerformed(ActionEvent e) { if(e.getSource() == inputfield) {out.println(inputfield.getText()); inputfield.setText(""); } } } class StreamListener extends Thread { BufferedReader in; TextArea output; public StreamListener(BufferedReader in, TextArea output) { this.in = in; this.output = output; this.start(); } public void run() { String line; try { for(;;) { line=in.readLine(); if(line == null) break; output.append(line); } } catch(IOException e) {output.setText(e.toString());} finally {output.append("\nConnection closed by server.");} } }
Next... page 11-10