public ChatServer(IServerConsole serverConsole) { chatters = new ArrayList<ChatHandler>(); ChatServer.serverConsole = serverConsole; try { ServerSocket listener = new ServerSocket(4711); print(WELCOME_MESSAGE); while (true) { Socket socket = listener.accept(); print("Connection accepted from " + socket.getInetAddress().getHostAddress()); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter output = new PrintWriter(socket.getOutputStream()); String username = null; String message = input.readLine(); StringTokenizer st = new StringTokenizer(message); // make sure it is a connect message. if (st.nextToken().equals(Requests.Connect) && st.hasMoreTokens()) { // second line must be empty if (input.readLine().equals("")) { username = st.nextToken(); // create new Chatter and ChatHandler Chatter chatter = createChatter(username, socket); ChatHandler chatHandler = new ChatHandler(chatter, this, input); chatters.add(chatHandler); chatHandler.setDaemon(true); chatHandler.start(); print("New Chatter created named: " + chatter.Name + " with id: " + chatter.Id); sendListToAll(); } else { output.print(formatCommand(KNordHeaderFields.Responses.Unsupported)); output.print(formatCommand(KNordHeaderFields.Responses.Disconnect)); print( "Disconnecting from " + socket.getInetAddress().getHostAddress() + " - UNSUPPORTED"); socket.close(); } } } } catch (IOException e) { print(e.getMessage()); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } serverConsole.getJFrame().dispose(); } }
protected static synchronized void print(String text) { serverConsole.print(text + "\r\n"); }