java Foundation (31): Network Communication Protocol, UDP, TCP

Keywords: Java socket network JDK ftp

1. Network Communication Protocol

Through computer network, many computers can be connected. The computers in the same network need to obey certain rules when connecting and communicating, which is just like the traffic rules when driving on the road. In computer networks, these rules of connection and communication are called network communication protocols. They uniformly stipulate the data transmission format, transmission rate, transmission steps and so on. Both sides of communication must abide by these rules to complete data exchange at the same time.

There are many kinds of network communication protocols. At present, the most widely used protocol is TCP/IP (Transmission Control Protocal/Internet Protoal Transmission Control Protocol/Internet Interconnection Protocol). It is a protocol group including TCP and IP protocols, UDP (User Data gram Protocol) protocols and some other protocols. Before learning specific protocols, we first understand the hierarchy of TCP/IP protocol group. Structure.

In the process of data transmission, it is required to send the same data as the received data. At this time, it is necessary to add a lot of information to the original data to ensure that the data format is identical in the transmission process. The hierarchy of TCP/IP protocol is relatively simple. It is divided into four layers, as shown in the figure.

In the figure above, the four layers of TCP/IP protocol are application layer, transport layer, network layer and link layer. Each layer is responsible for different communication functions. Next, the four layers are explained in detail.

Link Layer: Link Layer is used to define physical transmission channels, usually the driver protocol for some network connection devices, such as for optical fibers, Reticle Provided driver.

Network Layer: Network Layer is the core of TCP/IP protocol. It is mainly used to group the transmitted data and send the packet data to the target computer or network.

Transport Layer: Mainly to enable network programs to communicate, in the network communication, you can use TCP protocol, can also use UDP protocol.

Application Layer: Mainly responsible for the application protocol, such as HTTP protocol, FTP protocol, etc.

 

1.1 IP address and port number

 

 

In order to enable computers in the network to communicate, it is necessary to specify an identification number for each computer, through which to specify the computer receiving data or the computer sending data.

 

In TCP/IP protocol, this ID number is IP address, which can uniquely identify a computer. At present, the widely used version of IP address is IPv4, which is represented by four byte size binary numbers, such as: 000010000000000000001. Because the IP addresses in binary form are very difficult to remember and process, they are usually written in decimal form. Each byte is represented by a decimal number (0-255), and the numbers are separated by symbols such as "192.168.1.100".

 

With the continuous expansion of the scale of computer network, the demand for IP addresses is increasing. IPV4, an IP address represented by four bytes, is facing exhaustion. IPv6 came into being as the times require. IPv6 uses 16 bytes to represent IP addresses. Its address capacity is about 8 x 1028 times that of IPv4, reaching 2128 (counting all zero), which solves the problem of insufficient network address resources. Problem.

 

You can connect to the specified computer through an IP address, but if you want to access an application on the target computer, you also need to specify a port number. In computers, different applications are distinguished by port numbers. The port number is expressed by two bytes (16-bit binary number). Its range of values is 0-65535. Among them, the port number between 0-1023 is used for some well-known network services and applications. The user's ordinary applications need to use the port number above 1024 to avoid the port number being occupied by another application or service.

 

Next, an illustration is used to describe the role of IP addresses and port numbers, as shown in the following figure.

As can be seen clearly from the above figure, one computer in the network can access another computer through IP address and an application in the target computer through port number.

 

 

 

1.2 InetAddress

 

 

Understanding the role of IP addresses, let's look at the JDK under study to provide an InetAdderss class, which is used to encapsulate an IP address, and provides a series of methods related to IP addresses. The following table lists some common methods of the InetAddress class.

In the figure above, four common methods of InetAddress are listed. Among them, the first two methods are used to obtain instance objects of this class, the first method is used to obtain InetAddress objects representing the specified host, and the second method is used to obtain InetAddress objects representing the local host. The specified host name, IP address and so on can be obtained through the InetAddress object. Next, a case is presented to demonstrate the common methods of InetAddress, as shown below.

 

 

 

public class Example01 {
    public static void main(String[] args) throws Exception {
        InetAddress local = InetAddress.getLocalHost();
        InetAddress remote = InetAddress.getByName("www.itcast.cn");
        System.out.println("Native IP Address:" + local.getHostAddress());
        System.out.println("itcast Of IP Address:" + remote.getHostAddress());
        System.out.println("itcast The host name is:" + remote.getHostName());
    }
}

 

2. UDP and TCP Protocol

 

 

When introducing the structure of TCP/IP, two important advanced protocols in the transport layer are mentioned, UDP and TCP. UDP is the abbreviation of User Datagram Protocol, which is called User Datagram Protocol. TCP is the abbreviation of Transmission Control Protocol, which is called Transmission Control Protocol.

 

2.1 UDP Protocol

 

 

 

UDP is a connectionless communication protocol, that is, when data is transmitted, there is no logical connection between the sender and the receiver. Simply put, when a computer sends data to another computer, the sender will not confirm the existence of the receiver, it will send data, and when the receiver receives data, it will not give feedback to the sender whether it receives data.

 

Because the use of UDP protocol consumes less resources and has high communication efficiency, it is usually used for the transmission of audio, video and ordinary data, such as video conferencing, because the occasional loss of one or two data packets will not have a great impact on the reception results.

 

But when using UDP protocol to transmit data, UDP protocol is not recommended to transmit important data because UDP is connectionless and can not guarantee the integrity of data. The exchange process of UDP is shown in the following figure.

2.2 TCP Protocol

 

 

 

TCP protocol is a connection-oriented communication protocol, which establishes a logical connection between the sender and the receiver before transferring data, and then transfers data. It provides reliable and error-free data transmission between two computers. In TCP connection, it must be clear that the client and the server side, send the connection request from the client to the server side, each connection creation needs to go through "three shakes of hands". For the first handshake, the client sends a connection request to the server, waiting for the server to confirm. For the second handshake, the server sends back a response to the client, notifying the client that the connection request has been received. For the third handshake, the client sends confirmation information to the server again to confirm the connection. The whole interaction process is shown in the following figure.

 

Because of the connection-oriented characteristics of TCP protocol, it can ensure the security of data transmission, so it is a widely used protocol. For example, when downloading files, if the data reception is incomplete, it will lead to file data loss and can not be opened. Therefore, TCP protocol must be used when downloading files.

 

 

3. UDP communication

 

 

3.1 DatagramPacket

 

 

UDP is a connectionless protocol, so there is no need to establish a connection between the sender and the receiver when communicating. UDP communication is like a freight company sending goods between two terminals. Containers are used to load cargo when sending and receiving cargo at the terminal. The same is true for UDP communication. The data sent and received also need to be packaged with "containers". For this reason, a Datagram Packet class is provided in JDK. The instance object of this class is equivalent to a container, which is used to encapsulate the data sent or received in UDP communication.

 

To create a DatagramPacket object, you first need to understand how it is constructed. When creating the DatagramPacket object at the sender and receiver, the construction method used is different. The construction method of the receiver only needs to receive a byte array to store the received data, while the construction method of the sender not only receives the byte array that stores the transmitted data, but also specifies the IP address and port number of the sender.

 

Next, according to the content of API document, the construction method of Datagram Packet is explained in detail one by one.

When creating a Datagram Packet object, this constructor specifies the byte array and the size of the data encapsulated, without specifying the IP address and port number. Obviously, such objects can only be used at the receiver, not at the sender. Because the sender must specify the destination (ip address and port number) of the data, and the receiver does not need to know the source of the data, just need to receive the data.

 

 

When creating a Datagram Packet object, this method not only specifies the byte array and the size of the data encapsulated, but also specifies the destination IP address (addr) and port number of the data package. This object is usually used at the sender because the IP address and port number of the receiver must be specified when sending data, just as the receiver's address must be marked on the container for sending goods.

We explained the construction method of DatagramPacket above, and then explained the common methods in DatagramPacket class in detail, as shown in the table below.

 

3.2 DatagramSocket

 

 

Datagram Packet packages act as "containers" that encapsulate data at both the sender and the receiver. However, only "containers" are not enough to transport goods, and there is also a wharf. Only DatagramPacket data packages can not communicate in the program. For this reason, a DatagramSocket class is provided in JDK. The role of the DatagramSocket class is similar to that of a wharf. An instance object of this class can be used to send and receive DatagramPacket packets. The process of sending data is shown in the following figure.

 

When creating DatagramSocket objects at both the sender and the receiver, the construction methods used are also different. Here is a description of the common construction methods used in DatagramSocket classes.

 

This constructor is used to create the DatagramSocket object on the sender. When creating the DatagramSocket object, the port number is not specified. At this time, the system assigns a port number that is not used by other network programs.

 

This method can be used to create both the DatagramSocket object at the receiving end and the DatagramSocket object at the sending end. When creating the DatagramSocket object at the receiving end, a port number must be specified so that the specified port can be monitored.

We explained the construction method of DatagramSocket above, and then explained the common methods in DatagramSocket class in detail.

 

3.3 UDP Network Program

 

 

Explained the role of Datagram Packet and Datagram Socket, and then through a case study to learn their specific use in the program.

The following diagram illustrates the interaction between UDP sender and receiver

 

To realize UDP communication, we need to create a sender program and a receiver program. Obviously, only when the receiver program runs first, can we avoid the data loss caused by the data sent by the sender can not be received. Therefore, first of all, it is necessary to complete the writing of the receiver program.

UDP completes data transmission

 

 

/*
* Sending end
 * 1,Create DatagramSocket objects
 * 2,Create DatagramPacket objects and encapsulate data
 * 3,send data
 * 4,Release of Flow Resources
 */
public class UDPSend {
    public static void main(String[] args) throws IOException {
        //1,Establish DatagramSocket object
        DatagramSocket sendSocket = new DatagramSocket();
        //2,Establish DatagramPacket Object and encapsulate data
        //public DatagramPacket(byte[] buf, int length, InetAddress address,  int port)
        //Construct a datagram packet that is used to make the length of the packet equal to length The package is sent to the specified port number on the specified host.
        byte[] buffer = "hello,UDP".getBytes();
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("192.168.75.58"), 12306);
        //3,send data
        //public void send(DatagramPacket p) From then on, the socket sends data packets
        sendSocket.send(dp);
        //4,Release of Flow Resources
        sendSocket.close();
    }
}

 

UDP completes data reception

 

 

/*
 * UDP receiving end
 * 
 * 1,Create DatagramSocket objects
 * 2,Create DatagramPacket objects
 * 3,Received data is stored in the Datagram Packet object
 * 4,Get the content of the DatagramPacket object
 * 5,Release of Flow Resources
 */
public class UDPReceive {
    public static void main(String[] args) throws IOException {
        //1,Establish DatagramSocket object,And specify the port number
        DatagramSocket receiveSocket = new DatagramSocket(12306);
        //2,Establish DatagramPacket object, Create an empty warehouse
        byte[] buffer = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buffer, 1024);
        //3,Received data is stored in DatagramPacket In object
        receiveSocket.receive(dp);
        //4,Obtain DatagramPacket Object content
        //Who sent the data?  getAddress()
        InetAddress ipAddress = dp.getAddress();
        String ip = ipAddress.getHostAddress();//Got it. IP address
        //What data were sent?  getData()
        byte[] data = dp.getData();
        //How much data have been sent? getLenth()
        int length = dp.getLength();
        //Display the data received
        String dataStr = new String(data,0,length);
        System.out.println("IP Address:"+ip+ "Data is"+ dataStr);
        //5,Release stream resources
        receiveSocket.close();
    }
}

 

4. TCP Communication

 

 

TCP communication, like UDP communication, can realize the communication between two computers. Both ends of communication need to create socket objects.

 

The difference is that in UDP, only the sender and the receiver can send data arbitrarily without distinguishing between the client and the server.

 

TCP communication is a strict distinction between client and server. When communicating, the client must first connect to the server to achieve communication. The server can not actively connect to the client, and the server-side program needs to be started beforehand, waiting for the connection of the client.

 

In JDK, two classes are provided to implement TCP program. One is ServerSocket class, which is used to represent server side and the other is Socket class, which is used to represent client side.

 

When communicating, we first create a ServerSocket object on behalf of the server, which is equivalent to opening a service and waiting for the connection of the client. Then we create a Socket object on behalf of the client to send a connection request to the server, and the server responds to the request. The two establish a connection and start communicating.

 

 

4.1 ServerSocket

 

 

Through the previous learning, we know that when we develop TCP programs, we need to create server-side programs first. A ServerSocket class is provided in the java.net package of JDK. The instance object of this class can implement a server segment program. By consulting the API documents, we can see that the ServerSocket class provides a variety of construction methods. Next, we will explain the construction methods of ServerSocket one by one.

 

 

 

Using this constructor, when creating a ServerSocket object, you can bind it to a specified port number (the parameter port is the port number).

 

Next, learn the common methods of ServerSocket, as shown in the table.

 

ServerSocket object is responsible for monitoring a port number of a computer. After creating a ServerSocket object, it is necessary to continue calling the accept() method of the object to receive requests from the client. When the accept() method is executed, the server-side program will block until the client makes a connection request, and the accept() method will not return a Scoket object to communicate with the client, so the program can continue to execute downward.

 

 

4.2 Socket

 

 

The Server Socket object can realize the server-side program, but only the server-side program can not complete the communication. At this time, a client program is needed to interact with it. For this reason, JDK provides a Socket class to implement the TCP client program.

 

By consulting the API documents, we can see that the Socket class also provides a variety of construction methods. Next, we will explain the common construction methods of Socket in detail.

 

When using this construction method to create a Socket object, the server program running on the specified address and port will be connected according to the parameters, in which the parameter host receives a string-type IP address.

 

This method is similar in use to the second constructor, where the parameter address is used to receive an object of type InetAddress, which is used to encapsulate an IP address.

Among the above Socket construction methods, the first one is the most commonly used.

Next, learn about the common methods of Socket, as shown in the table.

 

 

Method statement

Function description

int getPort()

This method returns an int-type object, which is the port number of the Socket object connected to the server side.

InetAddress getLocalAddress()

This method is used to obtain the local IP address bound by the Socket object, and encapsulate the IP address as an object of InetAddress type to return.

void close()

This method is used to close the Socket connection and end the communication. Before closing sockets, all input/output streams associated with sockets should be shut down, because a good program should release all resources at the end of execution.

InputStream getInputStream()

This method returns an input stream object of type InputStream. If the object is returned by the Socket on the server side, it is used to read the data sent by the client side, and vice versa, to read the data sent by the server side.

OutputStream getOutputStream()

This method returns an OutputStream-type output stream object, which, if returned by a Socket on the server side, is used to send data to the client and vice versa to the server side.

 

 

In the common methods of Socket class, getInputStream() and getOutStream() methods are used to obtain input and output streams, respectively. When the connection between client and server is established, the data is interacted in the form of IO flow, thus realizing communication.

 

Next, a graph is used to describe the data transmission between the server and the client, as shown in the following figure.

 

4.3 Simple TCP Network Program

 

 

Understanding the basic usage of ServerSocket and Socket classes, in order to let you better grasp the use of these two classes, and then through a case of TCP communication to further learn. As shown in the figure below.

 

To realize TCP communication, we need to create a server-side program and a client-side program. In order to ensure the security of data transmission, we first need to implement the server-side program.

 

 

/*
 * TCP Server side
 * 
 * 1,Create server ServerSocket object (specify server port number)
 * 2,Open the server and wait for the client to connect. When the client connects, you can get the client Socket object that connects the server.
 * 3,Feedback to clients
 * 4,Closing Stream Resources
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        //1,Create a server ServerSocket Object (specify server port number)
        ServerSocket ss = new ServerSocket(8888);
        //2,Open the server and wait for the connection of the client. When the client connects, it can get to the client which connects the server. Socket object
        Socket s = ss.accept();
        //3,Feedback to clients
        /*
         * a,Get the client's output stream
         * b,On the server side, data is written to the client through the output stream of the client side.
         */
        //a,Get the client's output stream
        OutputStream out = s.getOutputStream();
        //b,On the server side, data is written to the client through the output stream of the client side.
        out.write("You've connected to the server".getBytes());
        //4,Closing Stream Resources
        out.close();
        s.close();
        //ss.close();  Server traffic is usually not closed
    }
}

 

Complete the server-side programming, and then write the client program.

 

 

/*
 * TCP Client
 * 
 * 1,Create client Socket object (specify the server address and port number to connect)
 * 2,Get feedback from the server
 * 3,Closing Stream Resources
 */
public class TCPClient {
    public static void main(String[] args) throws IOException {
        //1,Create Client Socket object,(Specify the server address and port number to connect to)
        Socket s = new Socket("192.168.74.58", 8888);
        //2,Get feedback from the server
        InputStream in = s.getInputStream();
        //Get the data in the capture stream
        byte[] buffer = new byte[1024];
        //Store the data in the stream into an array and record the number of bytes read
        int length = in.read(buffer);
        //Display data
        System.out.println( new String(buffer, 0 , length) );
        //3,Closing Stream Resources
        in.close();
        s.close();
    }
}

 

4.4 Cases of Document Upload

 

 

At present, most servers will provide file uploading function. Because file uploading requires data security and integrity, it is obvious that TCP protocol is needed to achieve it. Next, we use a case to realize the function of uploading pictures. As shown in the figure below. Original picture: file upload. bmp

 

 

 

First, we write a server-side program to receive pictures.

 

 

/*
 * File Upload Server
 *
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        //1,Create a server and wait for the client to connect
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket clientSocket = serverSocket.accept();
        //Which client to display Socket Connect to the server
        InetAddress ipObject = clientSocket.getInetAddress();//obtain IP Address object
        String ip = ipObject.getHostAddress(); //obtain IP Address string
        System.out.println("Sample, catch you, connect me!!" + "IP:" + ip);
        
        //7,Obtain Socket Input stream
        InputStream in = clientSocket.getInputStream();
        //8,Create the byte output stream of the destination   D:\\upload\\192.168.74.58(1).jpg
        BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream("D:\\upload\\192.168.74.58(1).jpg"));
        //9,hold Socket Data in the input stream, written to the byte output stream of the destination
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = in.read(buffer)) != -1){
            //Write to the destination byte output stream
            fileOut.write(buffer, 0, len);
        }
        
        //-----------------feedback information---------------------
        //10,Obtain Socket Output stream, Function: Write feedback to client
        OutputStream out = clientSocket.getOutputStream();
        //11,Write feedback to client
        out.write("Successful picture upload".getBytes());
        
        out.close();
        fileOut.close();
        in.close();
        clientSocket.close();
        //serverSocket.close();
    }
}

 

Write client to upload pictures

 

 

/*
 * File upload client
 * 
 * public void shutdownOutput()  Disabling the output stream of this Socket indirectly tells the server that the data has been written.
 */
public class TCPClient {
    public static void main(String[] args) throws IOException {
        //2,Create Client Socket,Connecting servers
        Socket socket = new Socket("192.168.74.58", 8888);
        //3,Obtain Socket Output stream in a stream: Used to write data to a server
        OutputStream out = socket.getOutputStream();
        //4,Create byte input stream, function: Used to read data source(picture)Bytes
        BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream("D:\\NoDir\\test.jpg"));
        //5,Write the picture data to Socket In the output stream of(Pass the data to the server)
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = fileIn.read(buffer)) != -1){
            //Write the data to Socket In the output stream of
            out.write(buffer, 0, len);
        }
        //6,Client sends data, end Socket Write operation of output stream to inform server side
        socket.shutdownOutput();

        //-----------------feedback information---------------------
        //12,Obtain Socket Input Flow Function: Reading Feedback Information
        InputStream in = socket.getInputStream();
        //13,Read feedback
        byte[] info = new byte[1024];
        //Store feedback information in info In an array, and record the number of bytes
        int length = in.read(info);
        //Display feedback results
        System.out.println( new String(info, 0, length) );
        
        //Closed flow
        in.close();
        fileIn.close();
        out.close();
        socket.close();
    }
}

 

4.5 Multithread version of file upload case

 

 

 

The server can receive files uploaded by multiple clients at the same time.

We need to modify the server-side code

 

 

/*
 * File upload multi thread version, server side
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        //1,Create a server and wait for the client to connect
        ServerSocket serverSocket = new ServerSocket(6666);
        
        //Realize the operation of multiple clients connecting to the server
        while(true){
            final Socket clientSocket = serverSocket.accept();
            //Start the thread to complete the data interaction with the current client
            new Thread(){
                public void run() {
                    try{
                        //Which client to display Socket Connect to the server
                        InetAddress ipObject = clientSocket.getInetAddress();//obtain IP Address object
                        String ip = ipObject.getHostAddress(); //obtain IP Address string
                        System.out.println("Sample, catch you, connect me!!" + "IP:" + ip);
                        
                        //7,Obtain Socket Input stream
                        InputStream in = clientSocket.getInputStream();
                        //8,Create the byte output stream of the destination   D:\\upload\\192.168.74.58(1).jpg
                        BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream("D:\\upload\\"+ip+"("+System.currentTimeMillis()+").jpg"));
                        //9,hold Socket Data in the input stream, written to the byte output stream of the destination
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while((len = in.read(buffer)) != -1){
                            //Write to the destination byte output stream
                            fileOut.write(buffer, 0, len);
                        }
                        
                        //-----------------feedback information---------------------
                        //10,Obtain Socket Output stream, Function: Write feedback to client
                        OutputStream out = clientSocket.getOutputStream();
                        //11,Write feedback to client
                        out.write("Successful picture upload".getBytes());
                        
                        out.close();
                        fileOut.close();
                        in.close();
                        clientSocket.close();
                    } catch(IOException e){
                        e.printStackTrace();
                    }
                };
            }.start();
        }

        //serverSocket.close();
    }
}

Posted by tcsnguy08 on Mon, 14 Oct 2019 02:40:41 -0700