Network programming for Java learning

1, Overview

Java is a language on the Internet. It provides support for network applications at the language level. Programmers can easily develop common network applications. The network class library provided by java can realize painless network connection. The underlying details of networking are hidden in the Java Native installation system and controlled by the JVM. Java implements a cross platform network library. Programmers face a unified network programming environment.

1. Computer network

The computers distributed in different geographical regions and special external equipment are interconnected with communication lines to form a large-scale and powerful network system, so that many computers can easily transfer information and share hardware, software, data information and other resources.

2. Purpose of network programming

  • Realize data exchange and communication with other computers directly or indirectly through network protocol.

3. Main problems

  • How to accurately locate one or more hosts on the network and locate specific applications on the hosts
  • How to transmit data reliably and efficiently after finding the host

It is worth noting that network programming= Web programming (WEB), the two architectures are B/S architecture and C/S architecture

4. Two elements

For the above two problems, there are two elements to solve the above problems.

  • IP and port number

  • Provide network communication protocol

    • OSI reference model: it is divided into 7 layers. The model is too idealized to be widely popularized on the Internet
    • TCP/IP reference model: it is divided into four layers. TCP/IP protocol, in fact, an international standard

2, IP and port number

1. IP address

IP address (InetAddress) can uniquely identify computers (communication entities) on the Internet. There are two main classification methods:

  • IPV4 and IPV6
    • IPV4: 4 bytes, 4 0-255. About 4.2 billion, 3 billion in North America and only 400 million in Asia. It was exhausted in early 2011. Expressed in dotted decimal system, such as 192.168.0.1;
    • IPV6: 128 bits (16 bytes), written as 8 unsigned integers, each integer is represented by four hexadecimal bits, and numbers are separated by colons, such as 3ffe:3201:1401:1280:c8ff:fe4d:db39:1984;
  • Public address (for World Wide Web use) and private address (for LAN use)
    • 192.168. The private address starts with the private address. The range is 192.168.0.0 – 192.168.255.255, which is specially used within the organization.

IP address is difficult to remember, so generally IP will have its corresponding domain name, such as Baidu com,jd.com, and has a special IP address and its corresponding domain name is 127.0.0.1 and localhost, which corresponds to the local loop address, that is, the local address.

In Java, InetAddress class is used to represent IP. The two methods to instantiate InetAddress are:

  • getByName(String host)
  • getLocalHost()
public static void main(String[] args) {
    try {
        // Get InetAddress object from IP address
        InetAddress inet1 = InetAddress.getByName("192.168.10.14");
        System.out.println(inet1);

        // Get InetAddress object by domain name
        InetAddress inet2 = InetAddress.getByName("www.atguigu.com");
        System.out.println(inet2);

        // Gets the local InetAddress object
        InetAddress inet3 = InetAddress.getByName("127.0.0.1");
        System.out.println(inet3);

        //Get local ip
        InetAddress inet4 = InetAddress.getLocalHost();
        System.out.println(inet4);

        //getHostName(): get the domain name corresponding to the InetAddress object
        System.out.println(inet2.getHostName());
        //getHostAddress(): get the IP address corresponding to the InetAddress object
        System.out.println(inet2.getHostAddress());
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

2. Port number

The port number identifies the process (program) running on the computer. Different processes have different port numbers, which are specified as a 16 bit integer 0-65535 Ports are classified as:

  • Recognized port: 0-1023, occupied by predefined service communication (e.g. HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
  • Registration port: 1024-49151, which is allocated to user processes or applications (for example, Tomcat occupies port 8080, MySQL occupies port 3306, and Oracle occupies port 1521)
  • Dynamic / private port: 49152-65535

The combination of port number and IP address yields a network Socket: Socket.

3, Network communication protocol

There must be some conventions to realize communication in computer network, that is, communication protocol, and formulate standards for * * rate, transmission code, code structure, transmission control steps, error control, etc** That's the problem. Computer network communication involves a lot of content, such as specifying source address and destination address. Encryption and decryption, compression and decompression, error control, traffic control, routing control, how to implement such a complex network protocol?

For the above problems, the layered idea of communication protocol is proposed in the network communication protocol. When making an agreement, break down the complex components into some simple components, and then combine them. The most commonly used compliance method is the hierarchical method, that is, the same layer can communicate, the upper layer can call the next layer, and there is no relationship with the next layer. Each layer does not affect each other, which is conducive to the development and expansion of the system.

1. TCP/IP protocol cluster

There are two very important protocols in the transport layer protocol:

  • Transmission control protocol (TCP)
  • User datagram protocol (UDP)

TCP/IP is named after its two main protocols: transmission control protocol (TCP) and network interconnection protocol (IP). It is actually a group of protocols, including multiple protocols with different functions and related to each other.

  • IP(Internet Protocol) protocol is the main protocol of network layer, which 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

2. TCP and UDP

2.1 TCP protocol

  • Before using TCP protocol, it is necessary to establish a TCP connection to form a data transmission channel;
  • Before transmission, the method of "three handshakes" is adopted for point-to-point communication, which is reliable;
  • Two application processes communicating with TCP protocol: client and server;
  • Large amount of data can be transmitted in the connection;
  • After transmission, the established connection needs to be released, which is inefficient.

2.2 TCP coding cases

The following three different cases will be used to demonstrate. It is worth noting that when running, you need to run the server first and then the client, which is the same as you have to have a mobile phone to send text messages.

Case 1: the client sends information to the server, and the server displays the data on the console

client

  • Create a Socket object to indicate the IP and port number of the server

  • Gets an output stream for outputting data

  • Operation of writing out data

  • close resource

/**
 * @Author xBaozi
 * @Description client
 * @Date 23:17 2022/1/2
 * @Param []
 * @return void
 **/
@Test
public void client() {
    Socket socket = null;
    OutputStream os = null;
    try {
        // 1. Create a Socket object to indicate the IP and port number of the server
        InetAddress inet = InetAddress.getByName("127.0.0.1");
        socket = new Socket(inet, 8899);
        // 2. Obtain an output stream for outputting data
        os = socket.getOutputStream();
        // 3. Write data
        os.write("Hello, this is the client".getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 4. Closure of resources
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Server

  • Create a ServerSocket on the server side and indicate its own port number
  • Call * * accept() * * to accept the socket from the client
  • Get input stream
  • Read data from input stream
  • close resource
/**
 * @Author xBaozi
 * @Description Server
 * @Date 23:18 2022/1/2
 * @Param []
 * @return void
 **/
@Test
public void server() {
    ServerSocket ss = null;
    Socket socket = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        // 1. Create a ServerSocket on the server side and indicate its own port number
        ss = new ServerSocket(8899);
        // 2. Call accept() to accept the socket from the client
        socket = ss.accept();
        // 3. Get input stream
        is = socket.getInputStream();
        //4. Read the data in the input stream
        //It is not recommended to write like this. There may be garbled code
        // byte[] buffer = new byte[1024];
        // int len;
        // while((len = is.read(buffer)) != -1){
        //     String str = new String(buffer,0,len);
        //     System.out.print(str);
        // }
        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() +
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(baos != null){
            //5. Close resources
            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();
            }
        }
    }
}

Case 2: the client sends the file to the server, and the server saves the file locally.

client

  • Create a Socket object to indicate the IP and port number of the server
  • Gets an output stream for outputting data
  • Gets a file stream for reading files
  • Write out the operation of the file
  • close resource
/**
 * @Author xBaozi
 * @Description client
 * @Date 15:27 2022/1/3
 * @Param []
 * @return void
 **/
@Test
public void client() throws IOException {
    // 1. Create a Socket object to indicate the IP and port number of the server
    InetAddress inet = InetAddress.getByName("127.0.0.1");
    Socket socket = new Socket(inet, 9090);
    // 2. Obtain an output stream for outputting data
    OutputStream os = socket.getOutputStream();
    // 3. Get a file stream for reading files
    FileInputStream fileInputStream = new FileInputStream(new File("wallhaven-1kqxkg.jpg"));
    // 4. Write out the operation of the file
    byte[] buffer = new byte[1024];
    int len;
    while ((len = fileInputStream.read(buffer)) != -1) {
        os.write(buffer, 0, len);
    }
    // 5. Close resources
    fileInputStream.close();
    os.close();
    socket.close();
}

Case 3: send files from the client to the server, and the server saves them locally. And return "send successfully" to the client.

client

  • Create a Socket object to indicate the IP and port number of the server
  • Gets an output stream for outputting data
  • Gets a file stream for reading files
  • Write out the operation of the file
  • Close the output of the file
  • Receive data from the server and display it on the console
  • close resource
/**
 * @Author xBaozi
 * @Description client
 * @Date 16:16 2022/1/3
 * @Param []
 * @return void
 **/
@Test
public void client() throws IOException {
    // 1. Create a Socket object to indicate the IP and port number of the server
    InetAddress inet = InetAddress.getByName("127.0.0.1");
    Socket socket = new Socket(inet, 9090);
    // 2. Obtain an output stream for outputting data
    OutputStream os = socket.getOutputStream();
    // 3. Get a file stream for reading files
    FileInputStream fis = new FileInputStream(new File("wallhaven-1kqxkg.jpg"));
    // 4. Write out the operation of the file
    byte[] buffer = new byte[1024];
    int len;
    while ((len = fis.read(buffer)) != -1) {
        os.write(buffer, 0, len);
    }
    // 5. Close the output of the file
    socket.shutdownOutput();
    // 6. Receive data from the server and display it on the console
    InputStream is = socket.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((len = is.read(buffer)) != -1) {
        baos.write(buffer, 0, len);
    }
    System.out.println(baos.toString());
    // 7. Close resources
    baos.close();
    is.close();
    fis.close();
    os.close();
    socket.close();
}

Server

  • Create a ServerSocket on the server side and indicate its own port number
  • Call accept() to accept the socket from the client
  • Get input stream
  • Get output stream
  • Read data from input stream
  • Get an output stream for feedback to the client
  • close resource
/**
 * @Author xBaozi
 * @Description Server
 * @Date 16:16 2022/1/3
 * @Param []
 * @return void
 **/
@Test
public void server() throws IOException {
    // 1. Create a ServerSocket on the server side and indicate its own port number
    ServerSocket ss = new ServerSocket(9090);
    // 2. Call accept() to accept the socket from the client
    Socket socket = ss.accept();
    // 3. Get input stream
    InputStream is = socket.getInputStream();
    // 4. Get output stream
    FileOutputStream fos = new FileOutputStream(new File("sent2.jpg"));
    // 5. Read the data in the input stream
    byte[] buffer = new byte[1024];
    int len;
    while ((len = is.read(buffer)) != -1) {
        fos.write(buffer);
    }
    System.out.println("Picture transfer complete");
    // 6. Obtain an output stream for feedback to the client
    OutputStream os = socket.getOutputStream();
    os.write("Picture received".getBytes());
    // 7. Close resources
    os.close();
    fos.close();
    is.close();
    socket.close();
    ss.close();
}

2.3 UDP protocol

  • Encapsulate the data, source and destination into data packets without establishing a connection;
  • The size of each packet is limited to 64K;
  • No matter whether the sending party is ready or not, the receiving party is uncertain about the receipt, so it is unreliable;
  • Can broadcast and send;
  • At the end of sending data, there is no need to release resources, low overhead and high speed.

2.4 UDP coding cases

  • Datagram socket and datagram packet
  • Establish sender and receiver
  • Create packet
  • Call Socket sending and receiving methods
  • Close Socket
/**
 * @Author xBaozi
 * @Description Sender
 * @Date 16:45 2022/1/3
 * @Param []
 * @return void
 **/
@Test
public void sender() throws IOException {
    // Create socket object
    DatagramSocket socket = new DatagramSocket();
    // Write the data to be sent
    String str = "I am UDP Missile sent by";
    byte[] data = str.getBytes();
    // Get local IP address
    InetAddress inet = InetAddress.getLocalHost();
    // Create packet
    DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
    // Call Socket sending method
    socket.send(packet);
    // close resource
    socket.close();
}
/**
 * @Author xBaozi
 * @Description receiving end
 * @Date 16:45 2022/1/3
 * @Param []
 * @return void
 **/
@Test
public void receiver() throws IOException {
    // Create socket
    DatagramSocket socket = new DatagramSocket(9090);
    // Create packet
    byte[] buffer = new byte[100];
    DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
    // Call Socket receiving method
    socket.receive(packet);
    // Print out data
    System.out.println(new String(packet.getData(),0,packet.getLength()));
    // close resource
    socket.close();
}

3,URL

URL(Uniform Resource Locator) is called uniform resource locator, which represents the address of a resource on the Internet. It is a specific URI, that is, the URL can be used to identify a resource, and also indicates how to locate the resource. Through URL, we can access various network resources on the Internet, such as the most common www and ftp sites. The browser can find the corresponding files or other resources on the network by parsing the given URL.

The basic structure of URL consists of five parts: < transport protocol > / / < host name >: < port number > / < file name > # fragment name? parameter list

  • #Segment name: anchor point, such as reading a novel, directly positioning to the chapter;
  • Parameter list format: parameter name = parameter value & parameter name = parameter value

To represent a URL, Java Net. The constructor of URL class declares that it throws a non runtime exception, which must be handled. It is usually caught with a try catch statement. The following are the common methods in the URL class

public static void main(String[] args) {
    try {
        URL url = new URL("http://localhost:8080/examples/hello.txt?username=Tom");
        // 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();
    }
}

At the same time, Tomcat local server is used to simulate downloading files from the network to the local server

@Test
public void test01() {
    HttpURLConnection urlConnection = null;
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        // Instantiate the URL object and provide the corresponding address
        URL url = new URL("http://localhost:8080/examples/hello.txt");
        // Get a URL connection of http protocol
        urlConnection = (HttpURLConnection) url.openConnection();
        // Connect to URL
        urlConnection.connect();
        // Get input stream
        is = urlConnection.getInputStream();
        // Instantiate output stream
        fos = new FileOutputStream("hello.txt");
        // Download file from URL address to local
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        System.out.println("Download complete");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // close 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();
        }
    }
}

Keywords: Java network JavaSE

Added by kylera on Thu, 06 Jan 2022 12:28:53 +0200