【问题标题】:How to make a chat program server send message to all connected clients in java如何使聊天程序服务器向Java中所有连接的客户端发送消息
【发布时间】:2020-01-06 12:12:57
【问题描述】:

我已经尝试过三次使这个程序每次都走得更远一些。我的程序应该是这样工作的:

客户端向服务器发送消息,然后服务器将消息发送给所有连接的客户端(包括发送消息的客户端)。当客户端收到消息时,他们会显示它。

我现在面临的问题是服务器只将消息发送给发送它的客户端,而其他客户端什么也没收到。我认为这是因为我接受客户的方式,或者至少与此有关

这是我当前的代码:

客户:

public class Client {

    protected static JTextArea textArea = new JTextArea(20, 30);
    protected static String sendMSG, getMSG;

    public static void main(String[] args) throws IOException {
        String hostName = args[0];
        String Username = args[1];
        boolean sending = true;

        try (
            Socket socket = new Socket(hostName, 1011);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        ) {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            //frame setup
            JFrame frame = new JFrame("chat client");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //text area
            JScrollPane scrollPane = new JScrollPane(textArea);

            //text field
            JTextField MSGText = new JTextField(5);

            //"send" button
            JButton sMSGB = new JButton("send");
            sMSGB.setPreferredSize(new Dimension(60, 30));
            sMSGB.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent event) {
                    sendMSG = MSGText.getText();
                    MSGText.setText("");
                    out.println("<" + Username + ">: " + sendMSG);
                }

            });

            //panel
            JPanel p = new JPanel();
            p.setLayout((new BoxLayout(p, BoxLayout.PAGE_AXIS)));
            p.add(Box.createVerticalStrut(5));
            p.add(scrollPane);
            p.add(Box.createVerticalStrut(5));
            p.add(MSGText);
            p.add(Box.createVerticalStrut(5));
            p.add(sMSGB);
            p.add(Box.createVerticalStrut(5));
            frame.getContentPane().add(p);

            //set frame visible
            frame.pack();
            frame.setVisible(true);

            System.out.println("<Client>: opened stream");

            while(sending) {

                /*while((sendMSG = stdIn.readLine()) != null) {
                    out.println("<" + Username + ">: " + sendMSG);
                }*/

                while((getMSG = in.readLine()) != null) {
                    System.out.println(getMSG);
                    textArea.append(getMSG + "\n");
                    //sending = false;
                }
            }
            //sending = true;
        } 
    }       
}

服务器:

public class Server {

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(1011)) {
            boolean listening = true;
            while(listening) {
                Socket socket = serverSocket.accept();
                List<PrintWriter> outs = new CopyOnWriteArrayList<PrintWriter>();
                new ServerThread(socket, outs).start();
                System.out.println("opened thread");
            }

        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

服务器线程:

public class ServerThread extends Thread {

    private final Socket socket;
    private final List<PrintWriter> outs;

    public ServerThread(Socket socket, List<PrintWriter> outs) {
        super("ServerThread");
        this.socket  = socket;
        this.outs = outs;
        System.out.println("Opened outs: " + outs.size());
    }

    private void sendToAll(String msg) {
        for(PrintWriter out: outs) {
            out.println(msg);
        }

    }

    public void run() {
        try (
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        ) {
            System.out.println("stream opened");
            outs.add(out);
            String getMSGs;

            while((getMSGs = in.readLine()) != null) {
                //out.println(getMSGs);
                sendToAll(getMSGs);
                System.out.println("msg received and sent");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

希望你能帮上忙。在此先感谢

【问题讨论】:

    标签: java networking tcp chat


    【解决方案1】:

    每次新客户端连接时,您都会重新初始化outs

                while(listening) {
                    Socket socket = serverSocket.accept();
                    List<PrintWriter> outs = new CopyOnWriteArrayList<PrintWriter>();
                    new ServerThread(socket, outs).start();
                    System.out.println("opened thread");
                }
    

    基本上是用空的outs 产生线程。您需要将输出流(或套接字)列表保留在循环之外,并在更新outs 列表时(当新客户端连接时)构建一种方法来向现有线程发出信号。

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      相关资源
      最近更新 更多