import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; public class Server { static final int PORT = 2012; private static HashSet<DataOutputStream> writers = new HashSet<DataOutputStream>(); public static void main(String[] args) throws Exception { System.out.println("The chat server is running."); ServerSocket listener = new ServerSocket(PORT); try { while (true) { new Handler(listener.accept()).start(); } } finally { listener.close(); } } private static class Handler extends Thread { private Socket socket; private DataInputStream in ; private DataOutputStream out; public Handler(Socket socket) { this.socket = socket; } public void run() { try { in = new DataInputStream(socket.getInputStream()) ; out =new DataOutputStream(socket.getOutputStream() ); writers.add(out); while (true) { byte [] input = new byte [1024]; int count = in.read(input); if (count > 0) { for (DataOutputStream writer : writers) { writer.write(input,0,count); } } if ( input.equals("bye.")) { break ; } } // end of while } catch (IOException e) { System.out.println(e); } finally { if (out != null) { writers.remove(out); } try { socket.close(); } catch (IOException e) { } } } } }
synchronized(writers) { (using the writers collection) }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)