Java – how to make two clients chat with each other?

This is not my homework (my homework is just chatting with clients and servers. It works normally, especially with your help [: -)]

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);
    }
}}

Solution

In this way, your two "clients" will act as clients and servers: listen to incoming content on the socket and send content through other sockets

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>