编程语言
首页 > 编程语言> > java – 多客户端聊天程序,向所有客户端广播聊天?

java – 多客户端聊天程序,向所有客户端广播聊天?

作者:互联网

我正在尝试制作一个可以容纳多个客户端的非常简单的聊天程序.我有一个多线程服务器,可以连接多个客户端,但服务器只与单个客户端通信(因为它应该,每个客户端都在自己的线程上)我需要帮助让服务器发送来自所有连接的所有消息每个客户的客户.我想我需要在线程之间共享一个对象?这是代码:

服务器:

import java.net.ServerSocket;
import java.net.Socket;


public class ThreadedCommandServer {

    public static void main(String[] args) throws Exception {
        System.out.println("Starting server....");
        int port = 8989;


        ServerSocket ss = new ServerSocket(port);


        while(true) {
            System.out.println("Waiting for connection from client...");
            Socket socket = ss.accept();
            ServerThread st = new ServerThread(socket);
            st.start();

        }
    }

}

服务器线程:

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ServerThread extends Thread {

    private Socket socket = null;
    private String s;

    public ServerThread(Socket s) {
        socket = s;

    }

    public void run() {
        try {
            InputStream is = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            s = (String) ois.readObject();
            System.out.println("received string: " + s);
            OutputStream os = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(s);
            System.out.println("sent object back to client...");
        } catch (Exception e) {
            System.out.println(e.toString());
        }

    }

}

客户:

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;


public class Controller {

private ClientFrame cf;
private String message;
private Socket socket;
private String response;

public Controller(ClientFrame cf) {
    this.cf = cf;
}


public void sendChat(String s) {
    message = s;
    System.out.println("FROM CONTROLLER: received: " + message);
    try {
    InetAddress i = InetAddress.getByName("localhost");
    socket= new Socket(i, 8989);
    OutputStream os = socket.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    System.out.println("FROM CONTROLLER: sending message to the server...");
    oos.writeObject(message);
    InputStream is = socket.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(is);
    System.out.println("getting string back from server....");
    response = (String) ois.readObject();
    cf.updateGUI(response);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

}

GUI:

   import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

    public class ClientFrame extends JFrame {

    private JTextArea chatArea;
    private JTextField type;
    private JButton submit;
    private JPanel upper;
    private JPanel lower;
    private BorderLayout bl;
    JScrollPane jsp;
    Controller c;

    public ClientFrame() {
        bl = new BorderLayout();
        upper = new JPanel();
        lower = new JPanel();
        chatArea = new JTextArea("chat goes here", 20, 30);
        c = new Controller(this);
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        type = new JTextField("type here", 20);
        jsp = new JScrollPane(chatArea);
        new SmartScroller(jsp);
        lower.add(type);
        submit = new JButton("send");
        submit.addActionListener(new Submit());
        type.addActionListener(new Submit());
        lower.add(submit);
        upper.add(jsp);
        this.setSize(400, 600);
        this.setLayout(bl);
        this.setTitle("MattChatt");
        this.add(upper, BorderLayout.NORTH);
        this.add(lower, BorderLayout.SOUTH);
        this.setVisible(true);
        this.setResizable(false);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void updateGUI(String s) {
        chatArea.append("\n" + s);
    }

    private class Submit implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (type.getText().equals("")) {
                System.out.println("no text entered");
            } else {
                System.out.println("submitted");
                c.sendChat(type.getText());
                type.setText("");

            }
        }

    }

    }

解决方法:

您无法访问您创建的所有ServerThreads.
您需要做的是将它们组合在一个集合中,例如ArrayList.

或者更好的是,HashMap,如果你想扩展你的应用程序以允许私人消息传递,你需要访问一个特定的ServerThread,并且使用HashMap你可以轻松地这样做.

无论如何……当发送消息时,您应该循环收集并将消息发送到与每个ServerThread关联的OutputStreams.

标签:java,multithreading,network-programming,server,tcp-ip
来源: https://codeday.me/bug/20190623/1274566.html