Chat сървър с отделни стаи

Клиент

package rooms;
import java.net.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;

public class Client {
    BufferedReader in;
    PrintWriter out;
    InetAddress addr;
    Socket socket;
    String name;
    int room;
    Gui g;
    Client(JFrame f){
        g = new Gui(f);
    }
    class Gui{
        JTextArea serv;
        JTextField cl;
        Gui (Frame f){
            f.setLayout(new BorderLayout());
            serv = new JTextArea(20,10);
            serv.setEditable(false);
            serv.setBackground(new Color(230,230,230));
            serv.setFont(new Font("SANS_SERIF", Font.BOLD, 14));
            cl = new JTextField(30);
            f.add("Center",new JScrollPane(serv));
            f.add("South",cl);
            cl.addActionListener(new SrvL());
            (new Rcv()).start();
        }
        class SrvL implements ActionListener{
            public void actionPerformed(ActionEvent e){
                try{
                    String st=cl.getText();
                    send(st);
                    cl.setText("");
                }
                catch (Exception ex){
                    System.out.println("exception: "+ex);
                    System.out.println("closing...");
                    try{
                        socket.close();
                    }
                    catch (Exception expt){
                        System.out.println(expt);
                    }
                }
            }
        }
        class Rcv extends Thread{
            public void run(){
                for(;;){
                    try { sleep(400); } catch (InterruptedException e){}
                    try{
                        serv.append(in.readLine()+"\n");
                        serv.setCaretPosition(serv.getDocument().getLength());
                    }
                    catch (IOException e1){break;}
                    catch(NullPointerException e2) {}  // 1-st time before start
                }
                System.out.println("thread receive from server closing...");
                try{
                    socket.close();
                }
                catch (Exception expt){
                    System.out.println(expt);
                }
                System.exit(0);
            }
        }
    }
    public void init()throws IOException{
        try{
            do{
                name = JOptionPane.showInputDialog("Please enter your name");
            } while((name == null)|| (name.length()==0));
            String server = null;
            InetAddress addr = InetAddress.getByName(server);
            System.out.println("addr = " + addr);
            socket = new Socket(addr, Chat.PORT);
            System.out.println("socket = " + socket);
            in =  new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            // Output is automatically flushed
            // by PrintWriter:
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),true);
        }catch (Exception e){
            System.out.println("exception: "+e);
            System.out.println("closing...");
            try{
                socket.close();
            }catch (Exception e2){
                System.out.println("no server running");
                System.exit(5);
            }
        }
        do{
            room=-1;
            try{
                room = Integer.parseInt(JOptionPane.showInputDialog("Please enter chat room (0-5)"));
            }
            catch (Exception e){}
        }while ((room<0)||(room>5));       //rooms range
        out.println(""+room);         // sending room to server
    }

    void send(String s){
        if(s.length()==0){
            int quit = JOptionPane.showConfirmDialog(null, "Exit chat");
            if(quit == 0) {
                System.out.println(quit);
                out.println("END");
                System.out.println("closing...");

                try{
                    socket.close();
                }
                catch (Exception expt){
                    //System.out.println(expt);
                }
                System.exit(0);
            }
        }
        else out.println(name+": "+s);
    }

    public static void main(String[] args )throws IOException{
        JFrame frame =new JFrame();
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        Client cl = new Client(frame);
        cl.init();
        frame.setTitle(cl.name+ " room:"+cl.room+ "  (empty line to exit)");
        frame.setSize(500,300);
        frame.setVisible(true);
    }
}

Сървър

package rooms;
import java.io.*;
public class Clients {
    PrintWriter arr[];
    Clients(){
        arr = new PrintWriter[0];      
    }
    synchronized void addElement(PrintWriter out){
        PrintWriter temp[]= new PrintWriter[arr.length+1];
        System.arraycopy(arr, 0, temp, 0, arr.length);
        temp[arr.length]= out;
        arr=temp;
    }
    synchronized void removeElement(PrintWriter out){
        for(int i=0;i<arr.length;i++){
            if(arr[i]==out){
                arr[i]=arr[arr.length-1];
                PrintWriter temp[]= new PrintWriter[arr.length-1];
                System.arraycopy(arr, 0, temp, 0, arr.length-1);
                arr=temp;          
                break;
            }
        }
    }
    synchronized PrintWriter elementAt(int i){
        return arr[i];
    }
    synchronized int size(){
        return arr.length;
    }
}

package rooms;
import java.io.*;
import java.net.*;
class ServeOneClient extends Thread {
    private Socket socket;
    private BufferedReader in;
    Clients clientWt;
    private PrintWriter out;
    private int room=-1;
    public ServeOneClient(Socket s,Clients[] clientAr)  throws IOException {
        System.out.println("new client apeared");
        socket = s;  
        in = new BufferedReader(
                new InputStreamReader(  socket.getInputStream()));
        out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(
                socket.getOutputStream()  )   ),    true);
        room = Integer.parseInt(in.readLine());
        System.out.println("room:"+room);
       clientWt=clientAr[room];
       clientWt.addElement((out ));
       System.out.println("clientWt.size room: " +room+" ->" +clientWt.size());   
        start();    // Calls run()      
  }
  public void run() {
    try {
        while (true) {
             String str = in.readLine();
             if (str.equals("END")) break;
            System.out.println("Echoing: " + str);
            System.out.println("clientWt.size room: " +room+" ->" +clientWt.size());
            for(int i =0;i< clientWt.size();i++){
                clientWt.elementAt(i).println(str);
            }
        }
        System.out.println("closing...");
    } catch (IOException e) {  }
   finally {
      try {
        socket.close();
      } catch(IOException e) {}
    }
    clientWt.removeElement(out);
    System.out.println("clientWt.size room: " +room+" ->" +clientWt.size());
  }
}
public class Chat {
  static final int PORT = 9080;
  public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);  
    System.out.println("Chat Server Started");
    Clients clientAr[]= new Clients[6];
    for(int i=0;i<clientAr.length;i++){
        clientAr[i]=new Clients();
    }
    try {
      while(true) {
        // Blocks until a connection occurs:
        Socket socket = s.accept();
        try {
          new ServeOneClient(socket,clientAr);
        } catch(IOException e) {
          // If it fails, close the socket,
          // otherwise the thread will close it:
          socket.close();
        }
      }
    } finally {
      s.close();
    }
  }
}