import java.net.*; import java.io.*; // -------------------------------------------------- public class ChatServer implements Runnable{ ServerSocket serverSocket = null; int port = 4444; public static void main(String[] args){ ChatServer chatter= new ChatServer(); Thread serverThread = new Thread(chatter); MyInput input = new MyInput(); String str; // Find out the port number if something other than the // default is desired try { if (args.length > 0) chatter.port = Integer.parseInt(args[0]); } catch (ArithmeticException e) { System.out.println("First argument is not an integer"); } // Start up the server thread serverThread.start(); // Look for command to terminate : #### do { str = input.get(); if (str != null) System.out.println(str); if (str.equals("####")) break; } while (str != null); // Shut down Server thread by closing his serverSocket try { if (chatter.serverSocket != null) chatter.serverSocket.close(); } catch (IOException except) { System.out.println("IOException in main"); } } public void run() { Socket nextSock; int nThreadCount=0; InetAddress iaddr; ChatServerThread childThread; ChatArea myChatArea = new ChatArea(); try { serverSocket = new ServerSocket(port); iaddr = InetAddress.getLocalHost(); System.out.println("getHostName = " + iaddr.getHostName()); System.out.println("getHostAddress = " + iaddr.getHostAddress()); for(;;)// Forever loop // We only exit when someone (main) closes // our socket. At that point we get an // IOException { nextSock = serverSocket.accept(); System.out.println(nThreadCount + " Another Thread Created"); myChatArea.chatArr[nThreadCount] = new Chat(); childThread =new ChatServerThread(nextSock, myChatArea, nThreadCount++); if (childThread != null) childThread.start(); else System.out.println("Unable to create a child thread"); } } catch (IOException e) { System.err.println("IOException in Server: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } // The following call should terminate all child threads myChatArea.setStopFlag(); System.out.println("Terminating ChatServer"); } }