java single server - Spraying words to all clients in multi client socket communication.

Asked 2 years ago, Updated 2 years ago, 118 views

Hello I'm making a chat with you. The code you've written so far has multiple clients connecting to one server, but it doesn't show anyone what one person wrote. If the client receives the while statement from the keyboard, it sends it to the server and receives it again. In order to spray it to several people and receive it from the client, there must be a separate while statement that plays a role from the server even if I don't write it on the keyboard. So I tried to write two threads on the client, but something didn't work well, so I restored it to the code that is currently running and posted a question... The examples on the Internet are implemented with gui, and the button action listener acts as a transfer, and other than that, they turn around the while statement waiting to be received in one thread, and I want to know what to do to make the chat happen in that code right now without gui. Thank you.

Server.java

package Socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    static List<ConnectionToClient> clients = new ArrayList<>();

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(5000);
            Socket socket = null;
            while ((socket = server.accept()) != null) {
                new ServerThread(socket).start();
            }
            server.close();
        } } catch (Exception e) {
        }
    }

    static class ServerThread extends Thread {
        Socket socket;
        ConnectionToClient conToClient;
        ServerThread(Socket socket) {
            this.socket = socket;
             conToClient = new ConnectionToClient(socket);
             clients.add(conToClient); 
        }
        public void run() {
            try {
                String input = "";
                while( (input = conToClient.read())!=null){
                    System.out.println(input);
                    conToClient.write(input);
                }
            } } catch (Exception e) {
            }
        }

        public void sendToAll(String message){
            for(ConnectionToClient client :clients){
                client.write(message);
            }
        }
    }

    static class ConnectionToClient {
        Socket socket;
        BufferedReader br;
        ObjectOutputStream oos;

        ConnectionToClient(Socket socket) {
            this.socket = socket;
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                oos = new ObjectOutputStream(socket.getOutputStream());

            } } catch (Exception e) {
            }
        }
        public String read(){
            try{
                return br.readLine();
            }catch(Exception e){return null;}
        }
        public void write(Object obj) {
            try {
                oos.writeObject(obj);
                oos.flush();
            } } catch (Exception e) {
            }
        }
    }
}

Client.java

package Socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {

        try {
            Socket socket = new Socket("127.0.0.1", 5000);
            ConnectionToServer server = new ConnectionToServer(socket);
            System.out.println("[INFO] connet complete");
            messageHandler mHandler = new messageHandler(server);
            mHandler.start();

        } } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class messageHandler extends Thread {
        ConnectionToServer server;

        messageHandler(ConnectionToServer server) {
            this.server = server;
        }

        public void run() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

                String initialLocation = "1 2";
                String input = "";
                String response = "";

                server.write(initialLocation);
                if ((response = server.read()) != null) {
                    drawMap(response);
                }

                while (true) {

                    input = keyboard.readLine();
                    if (input.equals("QUIT")) {
                        break;
                    }

                    server.write(input);
                    response = server.read();
                    drawMap(response);
                }
            } } catch (Exception e) {
            }
        }
    }

    static class ConnectionToServer {
        Socket socket;
        BufferedReader br;
        ObjectInputStream ois;
        PrintWriter pw;

        ConnectionToServer(Socket socket) {
            this.socket = socket;
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                pw = new PrintWriter(socket.getOutputStream());
                ois = new ObjectInputStream(socket.getInputStream());
            } } catch (Exception e) {
            }
        }

        public void write(String obj) {
            pw.println(obj);
            pw.flush();
        }

        public String read() {
            try {
                return (String) ois.readObject();
            } } catch (Exception e) {
                return null;
            }
        }
    }

    public static void drawMap(String command) {
        try {
            String[] yAndX = command.split(" ");
            int y = Integer.parseInt(yAndX[0]);
            int x = Integer.parseInt(yAndX[1]);
            String toPrint = "";
            for (int i = 0; i < 3; i++) {
                toPrint = "";
                for (int j = 0; j < 3; j++) {
                    if (y == i && x == j) {
                        toPrint += "* ";
                        continue;
                    }
                    toPrint += ". ";
                }
                System.out.println(toPrint);
            }
        } } catch (Exception e) {
        }
    }
}

java socket chatting

2022-09-21 17:26

1 Answers

messageHandler How about handling socket read in thread and socket write in main.

Server.java

package Socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    static List<ConnectionToClient> clients = new ArrayList<>();

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(5000);
            Socket socket = null;
            while ((socket = server.accept()) != null) {
                new ServerThread(socket).start();
            }
            server.close();
        } } catch (Exception e) {
        }
    }

    static class ServerThread extends Thread {
        Socket socket;
        ConnectionToClient conToClient;
        ServerThread(Socket socket) {
            this.socket = socket;
             this.conToClient = new ConnectionToClient(socket);
             clients.add(conToClient);
        }
        public void run() {
            try {
                String input = "";
                while( (input = conToClient.read())!=null){
                    System.out.println(input);
                    //conToClient.write(input);
                    sendToAll(input);
                }
            } } catch (Exception e) {
            }
        }

        public void sendToAll(String message){
            for(ConnectionToClient client :clients){
                System.out.println("message: " + message);
                client.write(message);
            }
        }
    }

    static class ConnectionToClient {
        Socket socket;
        BufferedReader br;
        ObjectOutputStream oos;

        ConnectionToClient(Socket socket) {
            this.socket = socket;
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                oos = new ObjectOutputStream(socket.getOutputStream());

            } } catch (Exception e) {
               System.out.println(e);
            }
        }
        public String read(){
            try{
                return br.readLine();
            }catch(Exception e){
                System.out.println(e);
                return null;
            }
        }
        public void write(Object obj) {
            try {
                oos.writeObject(obj);
                oos.flush();
            } } catch (Exception e) {
               System.out.println(e);
            }
        }
    }
}

Client.java

package Socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {

        try {
            Socket socket = new Socket("127.0.0.1", 5000);
            ConnectionToServer server = new ConnectionToServer(socket);
            System.out.println("[INFO] connet complete");
            messageHandler mHandler = new messageHandler(server);
            mHandler.start();
            String input="";
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            while(true) {
                input = keyboard.readLine();
                if(input.equals("QUIT")){
                    break;
                }
                server.write(input);
            }

        } } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class messageHandler extends Thread {
        ConnectionToServer server;

        messageHandler(ConnectionToServer server) {
            this.server = server;
        }

        public void run() {
            try {
                String initialLocation = "1 2";
                String response = "";
                server.write(initialLocation);
                while ((response = server.read()) != null) {
                    System.out.println("response:" +response);
                    //drawMap(response);
                }
            } } catch (Exception e) {
            }
        }
    }

    static class ConnectionToServer {
        Socket socket;
        BufferedReader br;
        ObjectInputStream ois;
        PrintWriter pw;

        ConnectionToServer(Socket socket) {
            this.socket = socket;
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                pw = new PrintWriter(socket.getOutputStream());
                ois = new ObjectInputStream(socket.getInputStream());
            } } catch (Exception e) {
            }
        }

        public void write(String obj) {
            pw.println(obj);
            pw.flush();
        }

        public String read() {
            try {
                return (String) ois.readObject();
            } } catch (Exception e) {
                return null;
            }
        }
    }

    public static void drawMap(String command) {
        try {
            String[] yAndX = command.split(" ");
            int y = Integer.parseInt(yAndX[0]);
            int x = Integer.parseInt(yAndX[1]);
            String toPrint = "";
            for (int i = 0; i < 3; i++) {
                toPrint = "";
                for (int j = 0; j < 3; j++) {
                    if (y == i && x == j) {
                        toPrint += "* ";
                        continue;
                    }
                    toPrint += ". ";
                }
                System.out.println(toPrint);
            }
        } } catch (Exception e) {
        }
    }
}


2022-09-21 17:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.