This is the 24th day of my participation in the August Text Challenge.More challenges in August

1. Network programming overview

  • Java is an Internet language that provides support for web applications at the language level, making it easy for programmers to develop common web applications.

  • Java provides a network class library that enables painless network connectivity, with the low-level details of networking hidden in Java’s native installation system and controlled by the JVM. And Java has realized a cross-platform network library, programmers face is a unified network programming environment.

  • Computer Network:

    The distribution of computers in different geographical areas and special external equipment with communication lines into a large, powerful network system, so that many computers can easily transfer information to each other, sharing hardware, software, data information and other resources.

  • The purpose of network programming:

    Directly or indirectly through the network protocol and other computers to achieve data exchange, communication.

  • There are two main problems with network programming:

    • How to accurately locate one or more hosts on the network; Locate a specific application on the host
    • How to reliably and efficiently transfer data after finding the host

2. Overview of network communication elements

  • Address of both parties
    • IP
    • The port number
  • Certain rules (i.e., network communication protocols. There are two sets of reference models)
    • OSI Reference Model: The model is too idealistic to be widely promoted on the Internet
    • TCP/IP Reference Model (or TCP/IP protocol) : the de facto international standard.
  • Network communication protocol

There are two main problems in network programming: * 1. How to accurately locate one or more hosts on the network; Locating the specific application on the host * 2. How to reliably and efficiently transfer data after finding the host * * 2. Two elements of network programming: * 1. Corresponding problem 1: IP address and port number * 2. Corresponding problem 2: Network communication protocol: TCP/IP reference model (application layer, transport layer, network layer, physical + data link layer) */
Copy the code

3. Communication elements 1: IP and port number

3.1 Understanding IP and instantiation of InetAddress class

  • IP address:

    InetAddress
    Copy the code
    • Uniquely identifies computers on the Internet (communication entities)
    • HostAddress: 127.0.0.1 hostName: localhost
    • IP address type 1: IPV4 and IPV6
      • IPV4: consists of four bytes, ranging from 0 to 255. About 4.2 billion, 3 billion all in North America, 400 million in Asia. It was exhausted in early 2011. The value is in dotted decimal notation, for example, 192.168.0.1
      • IPV6:128 (16 bytes), written eight unsigned integer, every integer with four hexadecimal said, between number by a colon (:) apart, such as: 3 ffe: 3201, 1401:1280: c8ff: fe4d: db39:1984
    • IP address type 2: Public IP address (for the World Wide Web) and private IP address (for the LAN). 192.168. Private IP addresses that start with 192.168.0.0 to 192.168.255.255 are reserved for internal use in organizations
    • Characteristics: Not easy to remember
  • Hosts on the Internet have two ways to represent addresses:

    • Domain name (hostName) : www.atguigu.com
    • IP address: 202.108.35.210
  • The InetAddress class mainly represents an IP address. There are two subclasses: Inet4Address and Inet6Address.

  • The InetAddress class object contains the domain name and IP address of an Internet host address: www.atguigu.com and 202.108.35.210.

  • Domain names are easy to remember. When you enter the domain name of a host when connecting to the network, the domain name server (DNS) converts the domain name into an IP address so that you can establish a connection with the host. ——- Domain name resolution

import java.net.InetAddress;
import java.net.UnknownHostException;

There are two main problems in network programming: * 1. How to accurately locate one or more hosts on the network; Locating the specific application on the host * 2. How to reliably and efficiently transfer data after finding the host * * 2. Two elements of network programming: * 1. Corresponding problem 1: IP and port number * 2. Corresponding problem 2: Provide network communication protocol: TCP/IP reference model (application layer, Transport layer, network layer, physical + data link layer) * * * IP and port number * * 1. IP: uniquely identifies a computer (communication entity) on the Internet * 2. In Java, InetAddress class is used to represent IP * 3. World Wide Web and LAN * 4. Domain name: www.baidu.com www.mi.com www.sina.com www.jd.com * port * 5. Localhost * * 6. How to instantiate InetAddress: two methods: getByName(String host), getLocalHost() * two methods: getHostName()/getHostAddress() * * 7. Port number: the process running on the computer. * Requirements: Different processes have different port numbers * Range: specifies a 16-bit integer ranging from 0 to 65535. * * 8. The combination of port number and IP address yields a network Socket: Socket */
public class InetAddressTest {
    public static void main(String[] args) {

        try {
            //File file = new File("hello.txt");
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");

            System.out.println(inet1);

            InetAddress inet2 = InetAddress.getByName("www.atguigu.com");
            System.out.println(inet2);

            InetAddress inet3 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);

            // Obtain the local IP address
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);

            //getHostName()
            System.out.println(inet2.getHostName());
            //getHostAddress()
            System.out.println(inet2.getHostAddress());

        } catch(UnknownHostException e) { e.printStackTrace(); }}}Copy the code

3.2 Understanding of port numbers

  • Port number identifies the process (program) that is running on the computer
    • Different processes have different port numbers
    • Is specified as a 16-bit integer0 ~ 65535.
    • Port types:
      • Recognized port:0 ~ 1023. Predefined service communication (e.g. HTTP port 80, FTP port 21, Telnet port 23)
      • Registration port:1024 ~ 49151. Assigned to a user process or application. (For example, Tomcat occupies port 8080, MySQL occupies port 3306, and Oracle occupies port 1521.)
      • Dynamic/private ports:49152 ~ 65535.
  • The combination of port number and IP address yields a network socket:Socket.

4. Communication elements 2: network protocol

  • Network communication protocol

    There must be some conventions to realize communication in computer network, namely communication protocol, which formulates standards for rate, transmission code, code structure, transmission control steps, error control and so on.

  • Problem: Network protocols are too complex

    Computer network communication involves a lot of content, such as specifying source address and target address, encryption and decryption, compression and decompression, error control, flow control, routing control, how to achieve such a complex network protocol?

  • The idea of communication protocol layering

    In making agreements, break down complex components into simple components and combine them. The most common composition approach is the hierarchical approach, in which one layer can communicate with another, and one layer can call the next, with no relationship to the next. Each layer does not affect each other, which is conducive to the development and expansion of the system.

4.1 comparison of TCP and UDP network communication protocols

  • There are two very important transport-layer protocols:
    • Transmission Control Protocol (TCP)
    • User Datagram Protocol (UDP).
  • TCP/IP, named after its two main protocols: Transmission Control Protocol (TCP) and Network Interconnection Protocol (IP), is actually a set of protocols, including several protocols with different functions and related to each other.
  • The Internet Protocol (IP) is a major Protocol at the network layer and supports data communication between networks.
  • From a more practical point of view, TCP/IP protocol model forms an efficient four-layer architecture, namely, physical link layer, IP layer, transport layer and application layer.
  • TCP protocol:
    • Before using TCP, you need to establish a TCP connection to form a data transmission channel
    • Before transmission, use “three handshake” mode, point – to – point communication, is reliable
    • TCP is used to communicate with two application processes: the client and the server.
    •  transfers a large amount of data in the connection, and needs to release the established connection, resulting in low efficiency
  • UDP protocol:
    • Encapsulate data, source, and destination into packets without establishing a connection
    • The size of each datagram is limited to 64K
    • Sending is unreliable regardless of whether the other party is ready or not, and the receiver does not acknowledge receipt
    • You can broadcast it
    • When data is sent, no resources are released, and the cost is low and the speed is fast

5. TCP network programming

1

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

Example 1: The client sends information to the server, and the server displays the data on the console */
public class TCPTest {

    / / the client
    @Test
    public void client(a)  {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1. Create a Socket object and specify the IP address and port number of the server
            InetAddress inet = InetAddress.getByName("192.168.14.100");
            socket = new Socket(inet,8899);
            //2. Get an output stream for output data
            os = socket.getOutputStream();
            //3. Write out data
            os.write("Hello, this is client HH.".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Resource shutdown
            if(os ! =null) {try {
                    os.close();
                } catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {try {
                    socket.close();
                } catch(IOException e) { e.printStackTrace(); }}}}/ / the server
    @Test
    public void server(a)  {

        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1. Create a ServerSocket on the server and specify its own port number
            ss = new ServerSocket(8899);
            2. Call Accept () to receive the socket from the client
            socket = ss.accept();
            //3. Get the input stream
            is = socket.getInputStream();

            // It is not recommended to write this, it may be garbled
// byte[] buffer = new byte[1024];
// int len;
// while((len = is.read(buffer)) ! = 1) {
// String str = new String(buffer,0,len);
// System.out.print(str);
/ /}
            //4. Read the data in the input stream
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while((len = is.read(buffer)) ! = -1){
                baos.write(buffer,0,len);
            }

            System.out.println(baos.toString());

            System.out.println("Received from:" + socket.getInetAddress().getHostAddress() + "The data");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(baos ! =null) {//5. Close the resource
                try {
                    baos.close();
                } catch(IOException e) { e.printStackTrace(); }}if(is ! =null) {try {
                    is.close();
                } catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {try {
                    socket.close();
                } catch(IOException e) { e.printStackTrace(); }}if(ss ! =null) {try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Copy the code

2

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

Example 2: The client sends a file to the server, and the server saves the file locally. * *@author subei
 * @createThe 2020-05-16 17:05 * /
public class TCPTest2 {

    /** * the exception mentioned here should be handled with try-catch-finally@throws IOException
     */
    @Test
    public void test(a) throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("164.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) ! = -1){
            os.write(buffer,0,len);
        }
        fis.close();
        os.close();
        socket.close();
    }

    /** * the exception mentioned here should be handled with try-catch-finally@throws IOException
     */
    @Test
    public void test2(a) throws IOException {
        ServerSocket ss = new ServerSocket(9090);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("1641.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) ! = -1){
            fos.write(buffer,0,len); } fos.close(); is.close(); socket.close(); ss.close(); }}Copy the code

3

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

Example 3: Send a file from the client to the server, and the server saves the file locally. And returns a message "Sent successfully" to the client. * And close the corresponding connection. * * /
public class TCPTest3 {
    /** * the exception mentioned here should be handled with try-catch-finally@throws IOException
     */
    @Test
    public void test(a) throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("164.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) ! = -1){
            os.write(buffer,0,len);
        }
        // Close the output of data
        socket.shutdownOutput();

        //5. Receive data from the server and display it to the console
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while((len1 = is.read(buffer)) ! = -1){
            baos.write(buffer,0,len1);
        }
        System.out.println(baos.toString());

        fis.close();
        os.close();
        socket.close();
        baos.close();
    }

    /** * the exception mentioned here should be handled with try-catch-finally@throws IOException
     */
    @Test
    public void test2(a) throws IOException {
        ServerSocket ss = new ServerSocket(9090);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("1642.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) ! = -1){
            fos.write(buffer,0,len);
        }

        System.out.println("Picture transfer completed");

        //6. The server sends feedback to the client
        OutputStream os = socket.getOutputStream();
        os.write("Hello, I have received the photo, nice view!".getBytes()); fos.close(); is.close(); socket.close(); ss.close(); os.close(); }}Copy the code

6. UDP network programming

  • Class DatagramSocket and DatagramPacket realize network program based on UDP protocol.
  • UDP datagramsockets are used to send and receive UDP datagramsockets. The system does not guarantee that UDP datagramsockets will be safely delivered to their destination or when they will arrive.
  • The DatagramPacket object encapsulates a UDP datagram, which contains the IP address and port number of the sender and the IP address and port number of the receiver.
  • Each UDP datagram provides complete address information, so there is no need to establish a connection between the sender and receiver. It’s like sending a package.
  • Process:
    1. DatagramSocket and DatagramPacket
    2. Establish sender and receiver
    3. Setting up packets
    4. Call the send and receive methods of the Socket
    5. Close the Socket

1, the sender and the receiver are two independent running programs

import org.junit.Test;

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

/** * Network programming for UDPd protocol */
public class UDPTest {

    / / the sender
    @Test
    public void sender(a) throws IOException {
        DatagramSocket socket = new DatagramSocket();

        String str = "I'm the UDP sender.";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

        socket.send(packet);
        socket.close();
    }

    / / the receiving end
    @Test
    public void receiver(a) throws IOException {
        DatagramSocket socket = new DatagramSocket(9090);

        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

        socket.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength())); socket.close(); }}Copy the code

7. URL programming

7.1 Understanding and instantiation of URL

import java.net.MalformedURLException;
import java.net.URL;

/** * URL * 1.URL: the uniform resource locator, which corresponds to the address of a resource on the Internet * 2. Format: * http://127.0.0.1:8080/work/164.jpg?username=subei * agreement hostname address parameter list * / port resources
public class URLTest {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://127.0.0.1:8080/work/164.jpg?username=subei");

// public String getProtocol() gets the protocol name of the URL
            System.out.println(url.getProtocol());
// public String getHost() gets the host name of the URL
            System.out.println(url.getHost());
// public String getPort() gets the port number of the URL
            System.out.println(url.getPort());
// public String getPath() gets the file path of the URL
            System.out.println(url.getPath());
// public String getFile() gets the file name of the URL
            System.out.println(url.getFile());
// public String getQuery() gets the query name of the URL
            System.out.println(url.getQuery());
        } catch(MalformedURLException e) { e.printStackTrace(); }}}Copy the code

7.2 URL network programming to achieve Tomcat server data download

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLTest1 {
    public static void main(String[] args) {
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://127.0.0.1:8080/work/164.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("day10\\1643.jpg");

            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) ! = -1){
                fos.write(buffer,0,len);
            }

            System.out.println("Download completed");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the resource
            if(is ! =null) {try {
                    is.close();
                } catch(IOException e) { e.printStackTrace(); }}if(fos ! =null) {try {
                    fos.close();
                } catch(IOException e) { e.printStackTrace(); }}if(urlConnection ! =null){ urlConnection.disconnect(); }}}}Copy the code

7.3. Differences between URIs, urls, and UrNs

  • A UNIFORM Resource Identifier (URI) is a uniform resource identifier that uniquely identifies a resource. A URL is a Uniform Resource locator, which is a specific URI. A URL can be used to identify a resource and specify how to locate the resource. URN, for Uniform Resource Name, identifies the resource by name, for example, mailto:[email protected]. That is, URIs are an abstract, high-level concept that defines a uniform resource identity, while urls and URNs are ways of specifying resource identities. Urls and UrNs are both urIs.
  • In Java URIs, an instance of a URI can represent either absolute or relative, as long as it follows the syntax rules for URIs. The URL class, on the other hand, not only conforms to semantics but also contains information to locate the resource, so it cannot be relative.