Java realizes the communication between client and server through socket

When learning socket communication in Java, the teacher assigned an assignment and took this opportunity to sort out the relevant knowledge. The topics are as follows:

Write client-server program and use Socket technology to realize communication. Both parties agree that the communication port is 6789. Server side function: after receiving the client information, first judge whether it is "BYE". If so, immediately send "BYE" to the other party, then turn off listening and end the program. If not, the received information is output on the screen, and the response information sent to the other party is input on the keyboard. Client function: when receiving "BYE" from the server, send "BYE" to the other party immediately, and then close the connection. Otherwise, continue to send information to the server.

First of all, we need to understand that socket is an abstraction between application services and TCP/IP communication. It divides the complex communication logic in TCP/IP protocol. For users, network connection can be realized through a set of simple API s.

Enter the code writing, because it is only for this problem, so add the judgment of parameters when starting the main function. If the startup parameter is not 0, start the server, otherwise start the client. The code is as follows:

public static void main(String[] args) {
        if(args.length > 0) {
            // Start the server side
            server();
        } else {
            // Start client
            client();
        }
}

The server side and the client side display each other's messages and their own input on the console through keyboard input. Here, I use two classes named Reader and Writer respectively to inherit Thread class to realize read-write operation. The code of class Reader is as follows:

class Reader extends Thread {
    private DataInputStream dis;
    private DataOutputStream dos;

    public Reader(DataInputStream dis, DataOutputStream dos) {
        this.dis = dis;
        this.dos = dos;
    }

    @Override
    public void run() {
        String str;
        while(true) {
            // read
            try {
                str = dis.readUTF();
                System.out.println("The other party said:" + str);
                // Receive "BYE" exit
                if("BYE".equals(str)) {
                    new Writer(dis, dos).start();
                    System.exit(0); // Program exit
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Class Writer code is as follows:

class Writer extends Thread {
    private DataInputStream dis;
    private DataOutputStream dos;

    public Writer(DataInputStream dis, DataOutputStream dos) {
        this.dis = dis;
        this.dos = dos;
    }

    @Override
    public void run() {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String str;
        while(true) {
            // write
            try {
                str = br.readLine();
                dos.writeUTF(str);
                dos.flush();
                if("BYE".equals(str)) {
                    // Receive "BYE" exit
                    new Reader(dis, dos).start();
                    System.exit(0);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

At this time, it becomes easy to write the server-side and client-side codes. The server-side codes are as follows:

    //  Server side
    public static void server() {
        System.out.println("=================server===================");
        try {
            // Set port number
            ServerSocket ss = new ServerSocket(6789);
            Socket s = ss.accept();
            // Packaging input / output stream
            OutputStream os = s.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream dos = new DataOutputStream(bos);
            InputStream is = s.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);

            // Read, start a thread to realize the read function
            new Reader(dis, dos).start();
            // Write, start a thread to realize the write function
            new Writer(dis, dos).start();

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

The client code is as follows:

    //  client
    public static void client() {
        System.out.println("=================client===================");
        try {
            Socket s = new Socket("localhost", 6789); // localhost 127.0.0.1 native address
            // Packaging input / output stream
            OutputStream os = s.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream dos = new DataOutputStream(bos);
            InputStream is = s.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);

            // Read, start a thread to realize the read function
            new Reader(dis, dos).start();
            // Write, start a thread to realize the write function
            new Writer(dis, dos).start();

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

So far, the code has been completed. When running, you should note that if you use IDEA to run, you need to click Edit Configurations first,

  Two items need to be modified. The first is Allow parallel run, because the client and server need to be started at the same time. If it is not checked, only one of them can be started. Program arguments also need to be modified. The judgment condition of whether to start the server or the client is based on the character length of program arguments. The server needs to be started first, so it needs to be modified at the same time, You can fill in the content freely. Here I fill in "123", and the screenshot is as follows:

  Click Run at this time, and the server is started successfully. Screenshot:

  Click Edit Configurations again to delete the contents after program arguments. Remember to click apply and ok. The screenshot is as follows:

  Click Run to find that the client also runs successfully. The screenshot is as follows:

  Enter on the server side or the client side to find that the conversation can be successful:

  Enter "BYE" to end the conversation. At the same time, you will also find the end running state of the program:

  The server also automatically ends the operation:

  So far, this problem has been successfully realized, but the thinking left is how to realize multi client communication. I didn't think of a particularly good solution. I hope I can get a good solution in future study.

Keywords: Java socket JavaSE http websocket

Added by R1der on Wed, 06 Oct 2021 23:32:45 +0300