Replicate message to all clients of a chat [closed]

1

I need to replicate a client's message to everyone who is logged in, except the client that sent it. Below are the classes I have so far. How could you replicate these messages?

public class Servidor {
  public static final int porta = 4444;
  private ServerSocket serverSocket;

public static void main(String[] args) {
    try {
        new Servidor().iniciarServidor();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void iniciarServidor() throws IOException {
    serverSocket = new ServerSocket(porta);
    System.out.println("Servidor esperando conexões..");
    while (true) {
        Socket socket = serverSocket.accept();
        ThreadServidor st = new ThreadServidor(socket);
        st.start();
    }
}

}

public class Cliente {
private static Socket socket;
private Scanner scanner;

public static void main(String[] args) throws UnknownHostException, IOException {
    new Cliente().iniciarCliente();
}

public void iniciarCliente() throws UnknownHostException, IOException {
    System.out.println("Digite seu nome: ");
    scanner = new Scanner(System.in);
    String nome = scanner.nextLine();
    socket = new Socket("localhost", 4444);
    PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader bf = new java.io.BufferedReader(new InputStreamReader(System.in));
    while (true) {
        String leitura = bf.readLine();
        pw.println(nome + ": " + leitura);
    }
}

}

public class ThreadServidor extends Thread {
private Socket socket;
PrintWriter printWriter = null;

public ThreadServidor(Socket socket) {
    this.socket = socket;
}

public void run() {
    try {
        String mensagem = null;
        BufferedReader bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while ((mensagem = bf.readLine()) != null) {
            System.out.println("Mensagem do cliente: " + mensagem);
        }
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
    
asked by anonymous 16.01.2016 / 10:00

1 answer

0

You basically need to store a list of client sockets and create a routine that iterates over all of them by typing in OutputStream of each.

Another alternative would be to create on the write threads server in addition to the incoming threads .

I've done a complete chat example using the second technique you can rely on.

Important parts are below.

The first is the map with the message queues to be sent to each client:

private final ConcurrentHashMap<String, BlockingDeque<Message>> users = new ConcurrentHashMap<>();

The map key is the name of the user and each value is a queue that stores messages to be sent to each client.

The BlockingDeque class is a special queue implementation where, if it is empty, the thread that tries to read an item from the queue waits for something to appear.

So, I create threads for each client that wait for the messages to be added to that queue, and as soon as some of the threads arrive, the client writes to the client.

The code of the thread that sends the messages is this:

for (;;) {
    final Message message = outgoingMessagesToClient.take();
    ...
    outputStream.writeObject(message);
    outputStream.flush();
    ....
}

To send a message to all users, simply add the message in all queues, like this:

private void sendMessageForAll(final Message message) {
    users.values().stream().forEach(q -> q.add(message));
}

Note that I simplified the code here to avoid more complex details, such as the case where there is an outgoing chat message that terminates the connection. My suggestion is to implement slowly and then you begin to enter more details,

    
16.01.2016 / 14:17