import java.net.*; import java.io.*; // The ChatReader thread reads incomming socket data and puts it into the // Chat Area so that all outbound threads can send it out class ChatReader extends Thread{ BufferedReader mySocketInput; int myIndex; ChatArea myChatArea; ChatReader(BufferedReader in, ChatArea cArea, int index) { super("ChatReaderThread"); mySocketInput = in; myIndex = index; myChatArea = cArea; } public void run(){ String inputLine; try { while ((inputLine = mySocketInput.readLine()) != null) myChatArea.putString(myIndex, inputLine); } catch (IOException e) { System.out.println("ChatReader IOException: "+ e.getMessage()); e.printStackTrace(); } System.out.println("ChatReader Terminating: " + myIndex); } } // ------------------------------------ // The main child thread waits for new information in the ChatArea, and // sends it out to the eagerly waiting clients class ChatServerThread extends Thread { private Socket socket = null; int myIndex; ChatReader myReaderThread; ChatArea myChatArea; public ChatServerThread(Socket socket, ChatArea cArea, int me) { super("ChatServerThread"); this.socket = socket; myChatArea = cArea; myIndex= me; System.out.println("Creating Thread "+myIndex); } public void run() { String outputLine; try { // First create the Streams associated with the Socket // Outbound Stream (actually a PrintWriter) PrintWriter outChat = new PrintWriter( socket.getOutputStream(), true); // Inbound Stream (actually a BufferedReader) BufferedReader inChat = new BufferedReader( new InputStreamReader( socket.getInputStream())); // Create a separate thread to handle the incomming socket data myReaderThread = new ChatReader(inChat, myChatArea, myIndex); myReaderThread.start(); // meanwhile, this thread will wait for new chatArea data and when // received, it will be dispersed to the connected client. do { outputLine = myChatArea.waitForString(myIndex); if (outputLine != null) outChat.println(outputLine); }while (outputLine != null); inChat.close(); outChat.close(); socket.close(); } catch (IOException e) { System.out.println("ChatServerThread IOException: "+ e.getMessage()); e.printStackTrace(); } System.out.println("ChatServerThread Terminating: " + myIndex); } }