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

时间:2014-04-22 23:11:03

标签: java network-programming

我想知道,如何向所有连接的客户端发送消息。更具体地说 - 所有ServerThreads。

以下是我的课程:

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();
}

}

服务器:http://pastebin.com/ZpBydK58

ServerThread:http://pastebin.com/CwAM72c3

1 个答案:

答案 0 :(得分:0)

将每个新的ServerThread分配给一个数组。然后你可以在Server中创建一个循环通过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);
        }
    }
}