import java.applet.*; import java.awt.*; import java.io.*; import java.net.*; public class ChatClient extends Applet { public static final int PORT = 2000; Socket s; DataInputStream in; PrintStream out; TextField user_name; TextField input_field; TextArea output_area; StreamListener listener; public void init () { try { this.showStatus ("Connecting to " + this.getCodeBase().getHost() + ":" + PORT + " ..."); s = new Socket (this.getCodeBase().getHost(), PORT); this.showStatus ("Connected to " + s.getInetAddress().getHostName() + ":" + s.getPort()); in = new DataInputStream (s.getInputStream ()); out = new PrintStream (s.getOutputStream ()); user_name = new TextField (20); input_field = new TextField (40); output_area = new TextArea (10, 40); output_area.setEditable (false); this.add (user_name); this.add (input_field); this.add (output_area); listener = new StreamListener (in, output_area); } catch (IOException e) { this.showStatus (e.toString ()); } } public boolean action (Event e, Object what) { if (e.target == input_field) { out.println (user_name.getText () + ": " + (String) e.arg); input_field.setText (""); return true; } return false; } } 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); output.appendText ("\n"); } } catch (IOException e) { output.appendText (e.toString ()); } finally { output.appendText ("Connection closed by server."); } } }