Finally, someone understood the TCP protocol and UDP protocol

There are three elements of network programming, namely IP address, port number and communication protocol. This paper mainly describes the two communication protocols of TCP and UDP, as well as the implementation of programming.

First, we need to know about IP address, port number and communication protocol.

1, IP address

Computers in the network use IP addresses for unique identification. There are two types of IP addresses: IPv4 and IPv6. IPv4 adopts decimal or binary representation. Decimal is a common representation, such as 192.168.1.131. IPv6 adopts hexadecimal representation, which is not commonly used.

How to view IP address related information:

Under Windows system, open cmd, enter the command ipconfig, and press enter to view. Under Linux or Mac system, open the terminal, use ifconfig command, and press enter to view.

2, Port number

Port number is an integer number label of application programs in the computer, which is used to distinguish different applications.

0 ~ 1024 is the port number that is not used or reserved by the system. 0 ~ 65535 is a valid port number, that is, when we want to define the port number for some programs, we should select an integer number in the range of 1024 ~ 65535.

For example, the port number of MySQL is 3306, the port number of SQL server is 1433, and the port number of Oracle is 1521.

Be sure to hide the port numbers corresponding to these databases in your mind. You will use the port number when connecting to the database in the future.

3, Communication protocol

Generally speaking, communication protocol is the rule of network communication, which is divided into TCP protocol and UDP protocol.

First: TCP protocol

English Name: transmission control protocol Chinese Name: Transmission Control Protocol Description: TCP is a connection oriented, reliable and byte stream based transport layer communication protocol.

For example: when making a phone call, both parties need to be connected before they can have a dialogue

Features: low efficiency and safe data transmission

Second: UDP protocol

English Name: User Datagram Protocol Chinese Name: datagram protocol description: UDP is a connectionless transport layer communication protocol.

For example, when sending text messages, there is no need for both parties to establish a connection. But, the size of datagram should be limited to 64k

Features: high efficiency, unsafe data transmission and easy packet loss

4, Three element relationship diagram and network model diagram

1. Relationship diagram of three elements of network programming

Note: the port number and IP address in the figure are demonstration, not true

2. OSI reference model and TCP/IP reference model

5, TCP programming

TCP is a transport layer communication protocol based on byte stream, so TCP programming is based on IO stream programming.

For the client, we need to use the Socket class to create objects. For the server side, we need to use ServerSocket to create an object, and call the accept() method through the object to listen for client access.

Client and server diagram:

Implementation steps of client and server:

Premise: create a project and create two modules (model s) in the project. One module is used to put the client-side related code and the other module is used to put the server-side related code.

The directory structure is shown in the figure below

client:

1. Create a Socket object and specify the port number of the server-side application and the IP address of the server-side host.

2. Use the Socket object to call the getOutputStream() method to get the byte output stream object.

3. Call write(byte[] buf) or write(int b) of the byte output stream to send the specified data to the server.

4. Remember to close the flow.

Server side:

1. Create a ServerSocket object and specify the port number of the application. The port number must be the same as that specified by the client.

2. Use the accept() method of the ServerSocket object to listen for requests sent by the client. The return value is the Socket object.

3. Call getInputStream() method of Socket object to get byte input stream object

4. Call the read(byte[] buf) or read() method of byte input stream object to obtain data.

5. Remember to turn off the stream.

example:

The client sends information to the server and displays it on the server.

Client class (client)

package cn.tkrnet.client;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {

        //Create a Socket object and specify the IP address to be sent to the server and the port number received by the server-side application
        //localhost represents the local IP address
        Socket client = new Socket("localhost",9000);

        //Get the output stream, which is used to send data to the server
        OutputStream os = client.getOutputStream();

        os.write("Java is my friend !".getBytes());
        System.out.println("Message sent");

        //Close flow
        os.close();
        client.close();
    }
}

Server class (server side)

package cn.tkrnet.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        System.out.println("--The server is turned on--");

        //Create a ServerSocket object. The port number here must be the same as that of the client
        ServerSocket server = new ServerSocket(9000);

        //Call the method accept() to listen for requests from clients
        Socket socket = server.accept();

        //Get input stream object
        InputStream is = socket.getInputStream();

        //Read data from input stream
        int b = 0;
        while ((b =is.read()) != -1){
            System.out.print((char)b);
        }
        //Close flow
        is.close();
        socket.close();
        server.close();
    }
}

Tip: when running the program, be sure to run the server-side program code first, and then the client-side program code. Because the client wants to send a request to the server, the premise is that the server must be turned on.

Running results of Server class (Server side):

--The server is turned on--

Client class (client) running result:

Message sent

After the Client class (Client side) runs, the Server class (Server side) receives the information, and the running result is:

--The server is turned on--
Java is my friend !

Case analysis:

After the server is started, the accept() method on the server is always listening until the client connects to the server, and then the server reads the data sent by the client from the stream.

With all due respect, this is a super invincible simple one-way communication example.

6, UDP programming

UDP uses datagrams for data transmission. There is no distinction between the client and the server, only the sender and the receiver. Neither of them will report an error when started first, but there will be data packet loss. The sent content has a word limit, and the size must be limited to 64k.

Implementation steps of sender and receiver:

Premise: create a project and create two modules (model s) in the project. One module is used to put the relevant codes of the sender and the other module is used to put the relevant codes of the receiver.

The directory structure is shown in the figure below

Sender:

1. When creating a DatagramSocket object, you can specify the port number of the application or not.

2. Prepare data to be sent

3. Create a DatagramPacket object to package the sent data. You need to specify four parameters: sending content, sending amount, sending place and the port number of the receiver.

4. Call the send() method of the DatagramSocket object to send data.

5. Remember to close the flow.

Receiver:

1. Create a DatagramSocket object and specify the port number of the receiver. This must be specified.

2. Create a byte type array to receive the data sent by the sender.

3. Create DatagramPacket object and prepare to receive data.

4. Call the receive() method of the DatagramSocket object to receive data.

5. Use the construction method of String class to convert the data in byte type array into String type and display it.

6. Remember to close the flow.

example:

The sender sends the information and the receiver receives the information and displays it.

Sender class (sender)

package cn.tkrnet.Sender;

import java.io.IOException;
import java.net.*;

public class Sender {
    public static void main(String[] args) throws IOException {

        //Create a datagram socket to accept or send, and specify the port number of the sender as 7770
        DatagramSocket ds = new DatagramSocket(7770);   //The port number can also be unspecified
        System.out.println("---Sender---");

        //Create a datagram object to send data
        byte[] b = "Java is my friend !".getBytes();

        //8800 is the port number of the receiver, netaddress Getbyname ("localhost") is the IP address of the host
        DatagramPacket dp = new DatagramPacket(b,b.length, InetAddress.getByName("localhost"),7788);

        ds.send(dp);    //Send datagram
        System.out.println("Data sent");
        //Close flow
        ds.close();
    }
}

Receiver class (receiver)

package cn.tkrnet.receiver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Receiver {
    public static void main(String[] args) throws IOException {
        System.out.println("---Receiver---");

        //Create a datagram socket object. The specified port number should be the same as the port number of the sender sending data
        //(not the sender's port number 7770, but the sender's port number 7788 for sending data)
        DatagramSocket ds = new DatagramSocket(7788);

        //Create an object to receive datagrams
        byte[] b = new byte[1024];
        DatagramPacket dp = new DatagramPacket(b,b.length);

        //receive data 
        ds.receive(dp);
        System.out.println(new String(b,0,dp.getLength()));
        //Close flow
        ds.close();
    }
}

Tip: when running the program, there will be no error when running the sender's program or the receiver's program first, but there may be data packet loss. Generally, we run the receiver's program code first and then the sender's program code.

Operation result of Receiver class (Receiver):

---Receiver---

Running result of Sender class (Sender):

---Sender---
Data sent

After the Sender class (Sender) runs, the Receiver class (Receiver) receives the information. The running result is as follows:

    ---Receiver---
    Java is my friend !

Case analysis:

Only when the receiver starts running first can there be a program with port number 7788, the sender can send data to the specified port number 7788, and the receiver can receive data.

To tell you the truth, this is also a super invincible simple one-way communication example.

Keywords: Java network udp TCP/IP

Added by toniknik1982 on Fri, 21 Jan 2022 03:40:44 +0200