package examples; import java.io.*; import java.net.*; import java.util.*; public class MyServer4 { public static void main(String[] args) { List clients = new LinkedList(); int count = 0; try { System.out.println("Binding ServerSocket..."); ServerSocket server = new ServerSocket(3459); server.setReuseAddress(true); while(true) { System.out.println("Waiting for Connection..."); Socket sock = server.accept(); System.out.println("Connection Received."); ClientHandler ch = new ClientHandler("Client"+count, sock); clients.add(ch); count++; ch.start(); } } catch(IOException ioe) {ioe.printStackTrace();} } private static class ClientHandler extends Thread { private String name; private Socket sock; private PrintWriter toClient; private Scanner fromClient; public ClientHandler(String name, Socket s) throws IOException { this.name = name; sock = s; toClient = new PrintWriter(sock.getOutputStream(), true); fromClient = new Scanner(new InputStreamReader(sock.getInputStream())); } public void run() { System.out.println(name + ": Waiting for input..."); String line; do { line = fromClient.nextLine(); System.out.println(name + ": " + line); if(line.startsWith("msg1")) toClient.println("msg2"); else if(line.startsWith("msg3")) toClient.println("msg4 with some text"); else if(line.startsWith("msg5")) toClient.println("msg6: I can't believe it's not butter"); else if(line.startsWith("msg7")) toClient.println("msg8: Break me off a peice of that kit kat bar"); toClient.flush(); } while(!line.equals("exit")); try { toClient.close(); fromClient.close(); sock.close(); } catch(IOException ioe){ioe.printStackTrace();} } } }