W
W
WestFree2017-11-22 22:18:01
Java
WestFree, 2017-11-22 22:18:01

How to send messages to all users?

The question is, how do I send messages to all users in the chat, and not just the one who sent it? Tell me, 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 {
            whileChatting();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            closeConnection();
        }
    }
    private void whileChatting() 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();
        }
    }
}
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();
        }
    }
}

and Client:
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 correctly add clients to the collection in order to send messages to all of them, so that it is like this: The client sent a message, the server received and sent back to everyone

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question