Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can make two clients chat with each other?

this is not my homework(my homework is just about doing chat with a client and server which it works correctly especially with your help[:-)] but I want to make two clients chat with each other,I don't know that when i get text from the first one how can I send that text to the other client.would you please help me.thanks.

public class MainServer {

static Socket client = null;
static ServerSocket server = null;



public static void main(String[] args) {
    System.out.println("Server is starting...");
    System.out.println("Server is listening...");

    try {
        server = new ServerSocket(5050);
    } catch (IOException ex) {
        System.out.println("Could not listen on port 5050");
        System.exit(-1);

    }
    try {
        boolean done = false;
        while (!done) {

            client = server.accept();
            System.out.println("Client Connected...");
            BufferedReader streamIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter streamOut = new PrintWriter(client.getOutputStream(),true);
            String line = streamIn.readLine();
            if (line.equalsIgnoreCase("bye")) {
                streamIn.close();
                client.close();
                server.close();
                done = true;
            } else {
                System.out.println(line);
                streamOut.println(line);
            }
        }

    } catch (IOException e) {
        System.out.println("IO Error in streams " + e);
    }
}}
like image 555
Johanna Avatar asked Dec 04 '25 10:12

Johanna


2 Answers

That's it, your two "clients" will both act as client and server : Listening to incoming things on a socket and sending things over an other sockets.

like image 152
Pico Avatar answered Dec 07 '25 00:12

Pico


On the server, you can keep a Set of all the clients that are currently connected to the server. The server should listen for messages (can do this with a ServerSocket, and clients connect with normal Sockets). Each time the server receives a message, it sends this message back to all clients in the Set, and the clients display the message.

EDIT: this is for a client-server system, where clients connect to a central server instead of directly to each other. If you want to do direct client-to-client, one of them will just have to act as the server, and you'll need to implement a chat UI in both.

like image 37
Kaleb Brasee Avatar answered Dec 07 '25 00:12

Kaleb Brasee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!