Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这样做的正确方式是什么?_Java_Sockets_Networking_Network Programming_Client Server - Fatal编程技术网

Java 这样做的正确方式是什么?

Java 这样做的正确方式是什么?,java,sockets,networking,network-programming,client-server,Java,Sockets,Networking,Network Programming,Client Server,我正在创建一个客户端-服务器客户端聊天应用程序。我已经为客户机和服务器编写了代码。但是我找不到一种方法来打印每个连接到服务器的客户端的联机客户端数量。这是我的密码 对于服务器:= 我希望在客户端上有一个文本区域,显示在特定时间连接到服务器的用户数。如果任何客户端单击退出按钮,该客户端将从此文本区域中删除。有人能帮我吗?我已经在同一上下文中发布了客户机-服务器通信的示例代码 请看一看 有关客户端-服务器通信的更多教程: 让我给你一个提示 您已经在users中提到了连接到服务器的客户端的名

我正在创建一个客户端-服务器客户端聊天应用程序。我已经为客户机和服务器编写了代码。但是我找不到一种方法来打印每个连接到服务器的客户端的联机客户端数量。这是我的密码

对于服务器:=


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

我已经在同一上下文中发布了客户机-服务器通信的示例代码

请看一看


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


让我给你一个提示

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

您可以在阵列中维护连接的客户端。通过这种方式,您将知道连接了多少个客户端

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
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