The question is, how can I send messages to all users in the chat, and not just to the one who sent it? Prompt, preferably without an auxiliary class that handles connections

import java.io.*; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Server extends Thread{ private PrintWriter printWriter; private BufferedReader bufferedReader; private Socket socket; private static List<MyClient>clients = Collections.synchronizedList(new ArrayList<>()); private MyClient client; public Server(Socket socket) { this.socket = socket; try { bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); printWriter = new PrintWriter(socket.getOutputStream(), true); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { whileChating(); } catch (IOException e) { e.printStackTrace(); }finally { closeConnection(); } } private void whileChating() throws IOException { String message = "SERVER msg: you are connecting " + socket.getInetAddress() + " : " + socket.getPort(); printWriter.println(message + "\r\n"); do { message = bufferedReader.readLine(); printWriter.println("Сообщение получил"); printWriter.println(message); System.out.println(message); }while (!message.equals("EXIT")); } private void closeConnection(){ System.out.println("Закрыите соединения"); printWriter.println("Пользователь отключился \r\n"); try { printWriter.close(); bufferedReader.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } 

Server startup:

 import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerRun { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(5656, 25)) { while (true){ Socket socket = serverSocket.accept(); new Server(socket).start(); } }catch (IOException e){ e.printStackTrace(); } } } 

Customer:

 import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; public class MyClient extends JFrame { private JTextField userInputText; private JTextArea chatWindow; private PrintWriter printWriter; private BufferedReader bufferedReader; private Socket socket; public MyClient(){ super("Client"); userInputText = new JTextField(); userInputText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendMessage(e.getActionCommand()); userInputText.setText(""); } }); add(userInputText, BorderLayout.NORTH); chatWindow = new JTextArea(); chatWindow.setEditable(false); add(new JScrollPane(chatWindow), BorderLayout.CENTER); setSize(300, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); startClient(); } private void startClient() { try { connectServer(); whileChating(); }catch (EOFException e){ showMessage("Клиент оборвал соединение"); }catch (IOException e){ e.printStackTrace(); }finally { closeConnection(); } } private void connectServer() throws IOException { showMessage("Connecting..."); socket = new Socket(); socket.connect(new InetSocketAddress("127.0.0.1", 5656), 2000); printWriter = new PrintWriter(socket.getOutputStream(), true); bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); showMessage("Connection ready"); } private void whileChating() throws IOException { String message; do { message = bufferedReader.readLine(); showMessage("\n" + message); }while (!message.equals("EXIT")); } private void closeConnection(){ showMessage("\nClose connection..."); try { printWriter.close(); bufferedReader.close(); socket.close(); } catch (IOException e) { e.getMessage(); } } public void sendMessage(String message){ printWriter.println(message); } private void showMessage(String msg){ SwingUtilities.invokeLater(new Runnable() { @Override public void run() { chatWindow.append(msg); } }); } } 

Tell me how to add clients to the collection in order to send them messages.

    1 answer 1

    This option:

    At the client:

    • register on the server, with getting id
    • send messages to the server along with your id

    On server:

    • instead of a list of clients, get a Map
    • when the client enters the chat, enter it in the map, the key is the client id, send the id back.
    • when sending a message from a client, take its id to exclude from the map and send a message to all those who remain.
    • How to understand the point: to register on the server, with the receipt of id And what message to send to the server along with the id? - Andrei
    • @ Andrei you have a list of chat clients, how do they get there? - Victor
    • No, I just want to do it, but I don’t know how - Andrei
    • one
      @Andrey why are you creating a server for each client? The server should be 1 for all clients - this is the first problem from which the following ensues. Rewrite the code so that all clients communicate on the same server. In this code, where each client is given a personal server, it is impossible to organize communication between clients. Although it is possible of course, but terrible crutches. Better stop now and redo it for 1 server - many clients. - Victor
    • @ Andrey, now you’ll have to write not communication between clients, but communication between servers. What is less convenient and more laborious, well, read more difficult - Victor