这样做的正确方法是什么?

时间:2014-04-06 07:08:06

标签: java sockets networking network-programming client-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

我想在客户端上有一个文本区域,显示在该特定时间连接到服务器的用户数。如果任何客户端单击退出按钮,将从此文本区域中删除客户端。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我已经在相同的上下文中发布了有关客户端 - 服务器通信的示例代码。

请查看Java Server with Multiclient communication.


有关客户端 - 服务器通信的更多教程:

Multiple clients access the server concurrently

A simple client-server chat application


让我给你一个提示。

  • 您已在users中提及连接到服务器的客户端的名称。
  • 为每个客户端添加窗口关闭侦听器,以便在断开任何客户端时将通知发送回服务器。
  • 删除用户名表单users
  • 那是

答案 1 :(得分:0)

您可以在阵列中维护已连接的客户端。通过这种方式,您将了解已连接的客户端数量。