// This example from the book Java in a Nutshell by David Flanagan. // Written by David Flanagan. Copyright (c) 1996 O'Reilly & Assc. // You may study, modify, this example for any purpose. // This example is WITHOUT WARRANTY either expressed or implied. // Modified by Roger Webster, Ph.D. import java.applet.*; import java.awt.*; import java.io.*; import java.net.*; public class ThreadClient extends Applet { public static final int PORT = 7777; Socket s; DataInputStream in; PrintStream out; TextField inputfield; TextArea outputarea; StreamListener listener; // Create a socket to communicate with a server on port 6789 of the // host that the applet's code is on. Create streams to use with // the socket. Then create a TextField for user input and a TextArea // for server output. Finally, create a thread to wait for and // display server output. public void init() { try { inputfield = new TextField(20); outputarea = new TextArea(5,20); outputarea.setEditable(false); add(inputfield); add(outputarea); this.show(); s = new Socket(this.getCodeBase().getHost(), PORT); in = new DataInputStream(s.getInputStream()); out = new PrintStream(s.getOutputStream()); System.out.println("after socket creation in applet!!"); listener = new StreamListener(in, outputarea); System.out.println("Connected to " + s.getInetAddress().getHostName() + ":" + s.getPort()); } catch (IOException e) {System.out.println(e.toString());}; } // When the user types a line, send it to the server. public boolean action(Event e, Object what) { if (e.target == inputfield) { out.println((String)e.arg); inputfield.setText(""); return true; } return false; } } // Wait for output from the server on the specified stream, and display // it in the specified TextArea. class StreamListener extends Thread { DataInputStream in; TextArea output; public StreamListener(DataInputStream 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.appendText(line); } } catch (IOException e) {output.setText(e.toString());} finally {output.setText("Connection closed by server.");} } }