Java Socket Programming: Event based multi-threaded chat server

429 Views Asked by At

I want to create a multithreaded chat server.

Let's say there's server, client1, client2 and client. If client 3 send "Hello" to the server, the server should then send "I received: Hello" to client1, client2 and client3.

My current approach could achieve: if client1 send "Hello" to the server, the server could send "I received: Hello" to client1, but not client2 and client3.

How can I achieve my goal?

My partial server code is:

       try (ServerSocket server = new ServerSocket(port)){
            System.out.println("Waiting for client connection-");
            while (true){
                Socket client = server.accept();
                System.out.println("Client applies for connection");

                Thread t = new Thread(() -> {
                    try {
                        serveClient(client);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
                t.start();
            }
        }

Where serveClient is

    public void serveClient(Socket client) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

            while (true){
                // read
                String line = reader.readLine();
                System.out.println("I received "+line);
                // write
                writer.write("I received " + line);
                writer.newLine();
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

My partial client code is:

        try (Socket socket = new Socket(hostname, port)){
            // create writer
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            Scanner sc = new Scanner(System.in);
            while (true) {
                System.out.print("Enter a String: ");
                String str = sc.nextLine();
                // send to server
                writer.write(str);
                writer.newLine();
                writer.flush();
                // get result from server
                String res = reader.readLine();
                System.out.println("Server response: "+ res);
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
            System.exit(-1);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

Thank you in advance for your help! Yige

0

There are 0 best solutions below