Java 向所有客户端发送批量消息

Java 向所有客户端发送批量消息,java,network-programming,Java,Network Programming,我想知道,如何向所有连接的客户端发送消息。更具体地说,是指所有服务器线程 以下是我的课程: public class Client { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Socket kkSocket = null; PrintWriter out = null; BufferedRea

我想知道,如何向所有连接的客户端发送消息。更具体地说,是指所有服务器线程

以下是我的课程:

public class Client {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    Socket kkSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try {
        kkSocket = new Socket("127.0.0.1", 4444);
        out = new PrintWriter(kkSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: localhost.");
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to: localhost.");
        System.exit(1);
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

    String fromUser, fromServer;

    while (!(fromUser = stdIn.readLine()).equalsIgnoreCase("#quit")) {
        out.println(fromUser);
        fromServer = in.readLine();
        System.out.println(fromServer);
    }

    out.close();
    in.close();
    stdIn.close();
    kkSocket.close();
}
}

服务器:


ServerThread:

将每个新的ServerThread分配给一个数组。然后,您可以在服务器中创建一个方法,通过ServerThread数组循环并向每个线程发送消息,并在ServerThread中创建一个方法来发送消息

例如:

public class Server {
    public final static int maxClients = 10000;
    public final static ServerThread[] clients = new ServerThread[maxClients];
    public static int numOfClients = 0;
    public static ServerSocket server;
    public static void main(String[] args){
        try{
            server = new ServerSocket(4444);
            while (numOfClients<maxClients){
                clients[numOfClients+1] = new ServerThread(server.accept());
                numOfClients++;
                clients[numOfClients].start();
            }
            while (true){
                server.accept().close();
            }
        }catch(Exception error){error.printStackTrace();}
    }
    public static void sendMessage(String message){
        for (int i=0;i<numOfClients;i++){
            clients[i].sendMessage(message);
        }
    }
}
公共类服务器{
公共最终静态int maxClients=10000;
public final static ServerThread[]clients=new ServerThread[maxClients];
公共静态int numOfClients=0;
公共静态服务器套接字服务器;
公共静态void main(字符串[]args){
试一试{
服务器=新服务器套接字(4444);
while(numof客户)