import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; // Must add this import java.applet.*; // ---------------------------------------------- // This thread reads in input stream from a socket and // appends the output to a TextArea object class DisplayThread extends Thread { TextArea m_text; BufferedReader inChat = null; DisplayThread (TextArea text, BufferedReader in) { m_text =text; inChat = in; } public void run() { System.out.println("Start DisplayThread "); String str; try { while ((str = inChat.readLine()) != null) { if (str.length() > 0) { m_text.append(str); m_text.append("\n"); } } } catch (IOException e) { System.out.println("inChat received an IOException: "+ e.getMessage()); e.printStackTrace(); } System.out.println("Display Thread Finishing"); } } // ----------------------------------------- public class ChatClientApplet extends Applet implements ActionListener{ TextArea tArea=new TextArea("",15,80,TextArea.SCROLLBARS_BOTH); TextField tinput=new TextField("",80); Socket chatSocket = null; PrintWriter outChat = null; BufferedReader inChat = null; DisplayThread myReader; public void init() { add(tArea); add (new Label( "Enter in your input into the following text field and hit the enter key")); add(tinput); tinput.addActionListener(this); } public void actionPerformed(ActionEvent e) { String str = tinput.getText(); System.out.println("My Input = " + str); if (myReader.isAlive()) outChat.println(str); tinput.setText(""); } public void stop() { System.out.println("Terminating"); try { outChat.close(); inChat.close(); chatSocket.close(); } catch (IOException e) { System.out.println("IOException in stop: " + e.getMessage()); } } public void start() { ChatClientApplet myApplet=new ChatClientApplet(); int port =4444; String hostStr, portStr; hostStr = getParameter("host"); portStr = getParameter("port"); System.out.println("Connect to host = "+ hostStr+ " port = " + portStr); // This will throw an exception if it doesn't exist or has junk in it. port = Integer.parseInt(portStr); try { chatSocket = new Socket(hostStr, port); // Create a PrintWriter object for socket output outChat = new PrintWriter( chatSocket.getOutputStream(), true); // Create a BufferedReader object for socket input inChat = new BufferedReader( new InputStreamReader( chatSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("UnknownHostException: " + e.getMessage()); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); } myReader = new DisplayThread(tArea, inChat); myReader.start(); } }