Simple implementation of Socket communication based on Java

Keywords: Java network socket udp

  • J3 - white start
  • Technology (TCP/IP # UDP # Socket)

Recently opened a project: https://gitee.com/j3_baiqi/communication

Welcome to point out the project structure, coding problems and business direction 😊😊😊😊😊😊.

1, What is a Socket

Encyclopedias:

Vernacular is the interactive interface based on the network communication protocol (the interface is the specification).

Since it is an interface, there must be an implementation, so all this talk is about a Socket communication implemented in Java. But before implementation, we still need to pave the way for two important protocols in network communication: TCP/IP and UDP.

2, Network communication protocol

In a computer, if two devices want to communicate, they must communicate in the same protocol, and the two protocols often mentioned in the network are TCP and UDP.

2.1 connection oriented TCP

"Connection oriented" is to establish a connection with the other party before formal communication. It is modeled according to the telephone system. For example, when you call someone, you have to wait until the line is connected and the other person picks up the microphone to talk to each other.

TCP protocol is a reliable, one-to-one, connection oriented communication protocol. TCP mainly ensures the reliability of data transmission in the following ways:

  1. When using TCP protocol for data transmission, the client and server often need to establish a "channel" first, and this channel can only be used by the client and server, so TCP transmission protocol can only face one-to-one connection.

  2. In order to ensure the accuracy of data transmission, TCP transmission protocol divides the data packet used for transmission into several parts (the size of each part depends on the network situation at that time) And then add a check byte in their header. When a part of the data is received, the server will verify the integrity and accuracy of this part. After verification, if the integrity and accuracy of the data are 100%, the server will require the client to start the transmission of the next part of the data. If the integrity and accuracy of the data are different from the original The server will ask the client to transmit this part again.

When using TCP transmission protocol, the client and server should first establish a "channel", and then close the "channel" after transmission. The former can be vividly called "three handshakes", while the latter can be called "four handshakes".

TCP protocol can provide reliable communication connection for applications, so that the byte stream sent by one computer can be sent to other computers on the network without error. Data communication systems with high reliability requirements often use TCP protocol to transmit data.

2.2 connectionless UDP protocol

"No connection" means that you don't have to establish a connection with the other party before formal communication, and send it directly regardless of the other party's status. It is very similar to mobile phone short message: when you send a short message, you just need to enter the other party's mobile phone number.

UDP transmission protocol is an unreliable, connectionless communication protocol that can realize many to one, one to many and one to one connections. UDP does not need to establish a channel before transmitting data, and it does not need to close the channel after data transmission. As long as the client sends a request to the server, the server will send all data at one time. UDP is in the number of transmissions Data integrity will not be verified during data transmission, and retransmission will not be required in case of data loss or data error. Therefore, a lot of time for verifying data packets will be saved. Therefore, the delay of the connection established with UDP will be lower than that established with TCP. UDP will not control the data transmission speed according to the current network conditions, so no matter the network conditions are good Whether it is bad or not, the server will send data at a constant rate. Although this will sometimes cause data loss and damage, this is very important for some real-time applications. Based on the above three points, UDP has faster data transmission speed, lower delay and better real-time performance, so it is widely used in the field of communication and video websites.

UDP is suitable for applications that only transmit a small amount of data at a time and do not require high reliability. For example, we often use the "ping" command to test whether the TCP/IP communication between two hosts is normal. In fact, "ping" The principle of the command is to send ICMP data packets to the other host, and then the other host confirms to receive the data packets. If the message of whether the data packets arrive is fed back in time, the network is connected.

For example, in the default state, a "ping" operation sends 4 packets. You can see that the number of packets sent is 4, and the number of packets received is 4 (because the other host will send back a packet confirming receipt after receiving it) This fully shows that UDP protocol is a non connection oriented protocol and does not establish a connection process. Because UDP protocol does not have a connection process, its communication efficiency is high; but because of this, its reliability is not as high as TCP protocol. QQ uses UDP to send messages, so sometimes it can not receive messages.

2.3 difference between the two

The biggest difference between TCP/IP and UDP is that TCP/IP is connection oriented and UDP is connectionless. TCP protocol and UDP protocol have their own strengths and weaknesses and are suitable for different communication environments. The differences between TCP protocol and UDP protocol are shown in the table below.

In actual use, TCP is mainly used in situations where file transmission accuracy is relatively high and not very urgent, such as e-mail, remote login, etc. sometimes in these application scenarios, even the loss of one or two bytes will cause irreversible errors, so TCP transmission protocol is generally used in these scenarios. UDP is widely used because it can improve transmission efficiency It is widely used for data transmission with large amount of data and low accuracy requirements. For example, when we watch video or listen to music on the website, the application is basically UDP transmission protocol.

Comparison chart:

3, Socket communication based on TCP/IP

Simple requirements: realize the basic communication between the client and the server. The client sends a message, and the server displays the client message and replies to the client.

Write the service code first

public class TcpSocketServer {

    /**
     * Server program
     */
    public void server() throws IOException {

        Scanner scanner = new Scanner(System.in);

        // The server listens to port 9528
        ServerSocket serverSocket = new ServerSocket(9528);
        System.out.println("Waiting for connection");
        Socket client = serverSocket.accept();
        System.out.println("Connection succeeded!");
        while (true) {
            // Get client input stream
            InputStream inputStream = client.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            // Message from client
            System.out.println("client:" + new String(bytes, 0, read, Charset.defaultCharset()));

            // Send something to the client
            System.out.print("Please enter:");
            String nextLine = scanner.next();
            if ("out".equals(nextLine)) {
                break;
            }
            client.getOutputStream().write(nextLine.getBytes(StandardCharsets.UTF_8));

        }


    }

    public static void main(String[] args) throws IOException {
        TcpSocketServer tcpSocketServer = new TcpSocketServer();
        tcpSocketServer.server();;
    }
}

Write the client code again

public class TcpSocketClient {

    /**
     * Client program
     */
    public void client() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Wait to connect to the server!");
        Socket socket = new Socket("127.0.0.1", 9528);
        System.out.println("Successfully connected to the server!");
        while (true) {
            // Send something to the server
            System.out.print("Please enter:");
            String s = scanner.next();
            if ("out".equals(s)) {
                break;
            }
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(s.getBytes(StandardCharsets.UTF_8));
            byte[] bytes = new byte[1024];

            // Read what the server sent
            InputStream inputStream = socket.getInputStream();
            int read = inputStream.read(bytes);
            System.out.println("Server:" + new String(bytes, 0, read, Charset.defaultCharset()));
        }
    }

    public static void main(String[] args) throws IOException {
        TcpSocketClient tcpSocketServer = new TcpSocketClient();
        tcpSocketServer.client();
    }
}

effect

4, Socket communication based on UDP

Similarly, use UDP to realize the above requirements

Server code

public class UdpSocketServer {

    /**
     * Server program
     */
    public void server() throws IOException {

        Scanner scanner = new Scanner(System.in);

        // The server listens to port 9528
        DatagramSocket serverSocket = new DatagramSocket(9528);
        while (true) {
            // Get client input stream
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            System.out.println("****The server has started, waiting for the client to send data");
            serverSocket.receive(datagramPacket);
            // Message from client
            System.out.println("client:" + new String(datagramPacket.getData(), 0, datagramPacket.getLength(), Charset.defaultCharset()));

            // Send something to the client
            System.out.print("Please enter:");
            String nextLine = scanner.next();
            if ("out".equals(nextLine)) {
                break;
            }
            byte[] bytes1 = nextLine.getBytes(StandardCharsets.UTF_8);
            DatagramPacket datagramPacket1 = new DatagramPacket(bytes1, bytes1.length, datagramPacket.getAddress(), datagramPacket.getPort());
            serverSocket.send(datagramPacket1);
        }


    }

    public static void main(String[] args) throws IOException {
        UdpSocketServer tcpSocketServer = new UdpSocketServer();
        tcpSocketServer.server();
        ;
    }
}

Client code

public class UdpSocketClient {

    /**
     * Client program
     */
    public void client() throws IOException {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            DatagramSocket datagramSocket = new DatagramSocket();
            datagramSocket.connect(new InetSocketAddress("127.0.0.1", 9528));
            String next = scanner.next();
            if ("out".equals(next)) {
                break;
            }
            byte[] bytes = next.getBytes(StandardCharsets.UTF_8);
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            datagramSocket.send(datagramPacket);

            // Get client input stream
            byte[] bytes1 = new byte[1024];
            DatagramPacket datagramPacket1 = new DatagramPacket(bytes1, bytes1.length);
            datagramSocket.receive(datagramPacket1);

            // Message from client
            System.out.println("Server:" + new String(datagramPacket1.getData(), 0, datagramPacket1.getLength(), Charset.defaultCharset()));

        }
    }

    public static void main(String[] args) throws IOException {
        UdpSocketClient tcpSocketServer = new UdpSocketClient();
        tcpSocketServer.client();
    }
}

effect:

If the above code is more rigorous, you should close the flow operation when you exit, but you know it. This is also to write a lot of judgment code for the sake of code simplicity and omitting redundant close flow operations, but you should pay attention to this in actual development.

5, Finally

For Socekt programming, that is, network programming, we can see that whether it is to connect or read data, it is blocked, and we have to wait for a certain time to continue.

If you do this in the main thread, it is a very bad thing for the program, and it is very cumbersome to develop a network program with Java's native API, except for senior engineers proficient in Socket. Therefore, NIO further encapsulates Socket programming and provides better programming methods to improve program efficiency and reduce development cost. In the next article, we will talk about it.

Well, that's the end of today's content. Pay attention to me. I'll see you next time

Access or reference:

Baidu Encyclopedia

Author contact:

QQ: 1491989462, be a good friend and make a point of praise.

  • Due to the blogger's lack of talent and learning, it is inevitable that there will be mistakes. If you find mistakes or prejudices, please leave a message to me and I will correct them.

  • If you think the article is good, your forwarding, sharing, likes and comments are my greatest encouragement.

  • Thank you for your reading. Welcome and thank you for your attention.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

CSDN: J3 - white start

Nuggets: J3 white

Know: J3 white

This is a technology in general, but keen to share; Experience is still shallow, but the skin is thick enough; A programmer who is young and has a good face, but doesn't rely on talent.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Posted by harsha on Sun, 05 Dec 2021 14:27:06 -0800