0

I am creating a client-server-client chat application. I have written the code for client and server. But I can't find a way to print the number of clients online on each and every client connected to the server. This is my code.

For server:=

public class ChatServer {

    Vector<String> users = new Vector<String>();
    Vector<HandleClient> clients = new Vector<HandleClient>();

    public void process() throws Exception {
        ServerSocket server = new ServerSocket(9999, 10);
        out.println("Server Started...");
        while (true) {
            Socket client = server.accept();
            HandleClient c = new HandleClient(client);
            clients.add(c);
        }  // end of while
    }

    public static void main(String... args) throws Exception {
        new ChatServer().process();
    } // end of main

    public void boradcast(String user, String message) {
        // send message to all connected users
        for (HandleClient c : clients) {
            if (!c.getUserName().equals(user)) {
                c.sendMessage(user, message);
            }
        }
    }

    class HandleClient extends Thread {

        String name = "";
        BufferedReader input;
        PrintWriter output;
        PrintWriter output1;
        public HandleClient(Socket client) throws Exception {
            // get input and output streams
            input = new BufferedReader(new InputStreamReader(client.getInputStream()));
            output = new PrintWriter(client.getOutputStream(), true);
            output1 = new PrintWriter(client.getOutputStream(),false);
            // read name
            name = input.readLine();
            users.add(name); // add to vector
            start();
        }

        public void sendMessage(String uname, String msg) {
            output.println(uname + ":" + msg);
        }

        public String getUserName() {
            return name;
        }


        public void run() {
            String line;

            try {
                while (true) {

                    line = input.readLine();
                    if (line.equals("end")) {
                        clients.remove(this);
                        users.remove(name);
                        break;
                    }
                    boradcast(name, line); // method  of outer class - send messages to all
                } // end of while
            } // try
            catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        } // end of run()
    } // end of inner class
} // end of Server

FOR CLIENTS:=

public class  ChatClient extends JFrame implements ActionListener {
    String uname;
    PrintWriter pw;
    BufferedReader br;
    JTextArea  taMessages;
    JTextField tfInput;
    JTextArea tOnline;
    JButton btnSend,btnExit;
    Socket client;


    public ChatClient(String uname,String servername) throws Exception {
        super(uname);  // set title for frame
        this.uname = uname;
        client  = new Socket(servername,9999);
        br = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
        pw = new PrintWriter(client.getOutputStream(),true);
        pw.println(uname);  // send name to server
        buildInterface();
        new MessagesThread().start();  // create thread for listening for messages
    }

    public void buildInterface() {
        btnSend = new JButton("Send");
        btnExit = new JButton("Exit");
        taMessages = new JTextArea();
        taMessages.setRows(10);
        taMessages.setColumns(50);
        taMessages.setEditable(false);
        tOnline = new JTextArea();
        tOnline.setRows(10);
        tOnline.setColumns(50);
        tOnline.setEditable(false);
        tfInput  = new JTextField(50);
        JScrollPane sp = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        add(sp,"Center");

        JPanel bp = new JPanel( new FlowLayout());
        bp.add(tfInput);
        bp.add(btnSend);
        bp.add(btnExit);
        bp.add(tOnline);
        add(bp,"South");
        btnSend.addActionListener(this);
        btnExit.addActionListener(this);
        setSize(500,300);
        setVisible(true);
        pack();
    }

    public void actionPerformed(ActionEvent evt) {
        if ( evt.getSource() == btnExit ) {
            pw.println("end");  // send end to server so that server know about the termination
            System.exit(0);
        } else {
            // send message to server
            pw.println(tfInput.getText());
        }
    }

    public static void main(String ... args) {

        // take username from user
        String name = JOptionPane.showInputDialog(null,"Enter your name :", "Username",
             JOptionPane.PLAIN_MESSAGE);
        String servername = "localhost";  
        try {
            new ChatClient( name ,servername);
        } catch(Exception ex) {
            out.println( "Error --> " + ex.getMessage());
        }

    } // end of main

    // inner class for Messages Thread
    class  MessagesThread extends Thread {
        public void run() {
            String line;
            try {
                while(true) {
                    line = br.readLine();
                    taMessages.append(line + "\n");
                } // end of while
            } catch(Exception ex) {}
        }
    }
} //  end of client

I want to have a text area on the client which shows the number of users connected to the server at that particular time. If any client clicks the exit button that client will be removed from this text area. Can someone help me out here?

arindrajit
  • 76
  • 1
  • 7

2 Answers2

0

I have already posted sample code on Client-Server communication in the same context.

Please have a look at Java Server with Multiclient communication..


Some more tutorials on Client-Server communication:

Multiple clients access the server concurrently

A simple client-server chat application


Let me give you a hint.

  • You are already mentioning the names of clients connected to server in users.
  • Add window closing listener for each client to send a notification back to server when any client is disconnected.
  • remove the user name form users
  • That's all
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
0

You can maintain the connected clients in array. This way you will know how many clients are connected .

Junaid Shirwani
  • 360
  • 1
  • 6
  • 20