import java.net.*; import java.io.*; import java.util.*; public class ChatServer { private ServerSocket server; public ChatServer(int port) { try { server = new ServerSocket(port); server.setReuseAddress(true); while(true) { Socket sock = server.accept(); (new Client(sock)).start(); } } catch(IOException ioe){ioe.printStackTrace();} } private class Client extends Thread { private Socket socket; private BufferedReader in; private PrintStream out; private String username; public Client(Socket s) throws IOException { socket = s; in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintStream(socket.getOutputStream()); } public void run() { String line; try { while(true) { line = in.readLine(); if(username == null) { username = line; continue; } System.out.println(username + ": " + line); } } catch(SocketException se) {} catch(IOException ioe){ioe.printStackTrace();} try { in.close(); out.close(); socket.close(); } catch(IOException ioe){ioe.printStackTrace();} } } public static void main(String[] args) { new ChatServer(Integer.parseInt(args[0])); } }