import java.net.ServerSocket; import java.net.Socket; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; class ClientThread extends Thread { private static int numberOfClients = 0; private static ArrayList allClients = new ArrayList(); private final int clientNumber = ++numberOfClients; private final Socket socket; private final BufferedReader in; private final PrintWriter out; public ClientThread(Socket s) throws IOException { socket = s; in = new BufferedReader( new InputStreamReader( socket.getInputStream())); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); // true: PrintWriter is line buffered System.out.println("Klienttråd " + clientNumber + " skapad."); out.println("Välkommen. Du är klient nummer " + clientNumber + "."); allClients.add(this); // If any of the above calls throw an // exception, the caller is responsible for // closing the socket. Otherwise the thread // will close it. start(); // Starts the thread, and calls run() } public void run() { try { while (true) { String inline = in.readLine(); System.out.println("Klienttråd " + clientNumber + " tog emot: " + inline); // Not: inline == "quit" if (inline == null || inline.equals("quit")) break; out.println("Du sa '" + inline + "'"); Iterator i = allClients.iterator(); while (i.hasNext()) { ClientThread t = (ClientThread)i.next(); if (t != this) t.out.println("Från klient " + clientNumber + ": " + inline); } } System.out.println("Klienttråd " + clientNumber + ": Avslutar..."); } catch(IOException e) { System.out.println("Klienttråd " + clientNumber + ": I/O-fel"); } finally { try { socket.close(); } catch(IOException e) { System.out.println("Klienttråd " + clientNumber + ": Socketen ej stängd"); } allClients.remove(allClients.indexOf(this)); } } // run } // class ClientThread public class MultiServer { public static final int PORT = 2000; public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(PORT); System.out.println("Server-socketen: " + s); System.out.println("Servern lyssnar..."); try { while(true) { // Blocks until a connection occurs: Socket socket = s.accept(); System.out.println("Uppkoppling accepterad."); System.out.println("Den nya socketen: " + socket); try { ClientThread t = new ClientThread(socket); System.out.println("Ny tråd skapad."); System.out.println("Den nya tråden: " + t); } catch(IOException e) { // If the constructor fails, close the socket, // otherwise the thread will close it: socket.close(); } } } finally { s.close(); } } // main } // MultiServer