Network programming in java

Keywords: Java Back-end

1, What is network?

In the computer field, the network is a virtual platform for information transmission, reception and sharing. Through it, all points, surfaces and bodies are connected together, so as to realize the sharing of these resources.
Function: information transmission and resource sharing
A little: resource sharing is free

2, OSI seven layer reference model and TCP/IP four layer reference model  

  Computer network is a collection of many autonomous computers connected by communication lines. What rules are used for communication between various components is the problem of network model research.
    Network model generally refers to OSI seven layer reference model and TCP/IP four layer reference model. These two models are most widely used in the network.
    OIS seven layer reference model: application layer / presentation layer / session layer / transport layer / network layer / data link layer / physical layer

    TCP/IP four layer reference model: application layer, transport layer, IP layer [Internet layer], network interface layer [network connection layer]

3, Four elements of computer network

1.IP address
        All communication devices (computers, mobile phones, televisions, etc.) in the network will be assigned an IP address.
        Before communication, these devices must be connected to the network through the network card of the communication device.
        The network card belongs to a hardware, and all network cards have a fixed network card address when they leave the factory, and the network card address (MAC address) is unique in the world.
        View network card address (MAC address)
        1. Enter ipconfig/all in the command prompt window to query the details related to IP (mac address)
        2.Linux operating system can query IP(Mac address) related details by using ifconfig
What is the relationship between fixed network card address (Mac address) and IP address?
    For example: fixed network card address (Mac address)----   FA-A2-D6-BF-A4-A1
        IP address --------------------------------------- [192.168.1.255]
    All network cards have a unique physical address, but this address is very difficult to remember. So each network card is assigned a logical address, which is the IP address. In the process of communication, you can find the device in the network according to this logical address.
    The IP address is also the identification of a communication terminal in the network
What is the relationship between IP address and domain name?
    Because the IP address is not easy to remember, the inheritance binds a name to each IP, which is the domain name.
    [FA-A2-D6-BF-A4-A1]---[192.168.1.255]----https://www.baidu.com/ domain name
    The default IP address of this machine is 127.0.0.1; It has a corresponding default domain name localhost
2.DNS server [domain name resolution server]
    Domain name resolution:
    1. Local resolution:
        In our operating system, if we find the IP address corresponding to the current domain name in a hosts file, this IP address will be used. “C:\Windows\System32\drivers\etc\hosts”
      2.DNS server resolution
        If the first step of resolution fails, it will be resolved to the DNS server in the network. The DNS server will set the global domain name and IP in it. If the DNS server fails to resolve, there is a problem with the current domain name.
3. Agreement
    Protocol: the communication rules to be observed by both parties when communicating.
    Later, we will encounter many protocols (Advanced protocol, application protocol: http, ftp/https).
    The protocol we introduced in java network programming belongs to the underlying protocol [TCP/UDP], and all high-level protocols belong to the underlying protocol
4. Port
    We can find the equipment of the specific communication terminal in the network through ip. The specific resource (software) information in the device needs to be accessed. At this time, because there must be many resources (software) running in the device, each resource (software) must be given a unique number (identification). Through this identification, we can ensure that we can access the specific resource (software) of the specified ip address without error.
      Port: it is the unique identification of an application on a device (computer, mobile phone). Any software running in the equipment will have a unique number bound to its whole software as long as it is started.
      The port starts from 0 to 65535. The port number between 0 and 1024 has been allocated to the application of the local operating system. Therefore, if we need to bind the port later, it must be greater than 1024
      Port is actually the entrance to access the program running on this computer when entering this computer.

4, Use of netAddress class?  

java.net package class InetAddress   This class represents an Internet Protocol (IP) address.
public class InetAddress implements java.io.Serializable 
Constructor of InetAddress class
Default modifier InetAddress() {}
In our own Java programs, we cannot create InetAddress class objects through new + construction methods.
We need to use the following two static methods to get the InetAddress class object.
     static   InetAddress getLocalHost() returns the InetAddress object containing the native IP address.
     static   InetAddress getByName(String   host) get the InetAddress object containing the ip address corresponding to the domain name according to the domain name.
Instance method:
      String getHostAddress() returns the IP address string (expressed as text).
     String getHostName() gets the host name of this IP address.
For example:

package com.wangxing.test1;

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

public class InetAddressTest {
	public static void main(String[] args) throws Exception {
		//1. Get the ip address and computer name of the machine
		//Get the InetAddress object containing the native ip address
		InetAddress benji=InetAddress.getLocalHost();
		//Get native IP
		String benjiIP=benji.getHostAddress();
		//Gets the host name of this IP address.
		String benjiName=benji.getHostName();
		System.out.println(benjiIP);
		System.out.println(benjiName);
		//2. Obtain the InetAddress object containing the ip address corresponding to the domain name according to the domain name.
		//String host="https://www.baidu.com "; error
		String host="baidu.com";
		//Create the IP address of this domain name based on the domain name
		InetAddress baiduInetAddress=InetAddress.getByName(host);
		String baiduip=baiduInetAddress.getHostAddress();
		String baidu=baiduInetAddress.getHostName();
		System.out.println("Baidu IP Address:"+baiduip+",name:"+baidu);
	}
}

 

5, What is the difference between URL and URI?  

URI, Uniform Resource Identifier (URI), means that every available resource on the web, such as HTML document, image, video clip, program, etc., is identified by a URI.
A URI usually consists of three parts:
     ① Naming mechanism of resources;
     ② The host name where the resource is stored;
     ③ The name of the resource itself.
URL s are a subset of URI s. It is the abbreviation of Uniform Resource Locator, which is translated as "Uniform Resource Locator".
URL can be used to describe various information resources in a unified format, including files, server addresses and directories.
     A URL is an implementation of the URI concept.
     The format of the URL consists of three parts:  
     ① The first part is the agreement (or service mode).
     ② The second part is the host IP address (sometimes including port number) where the resource is stored.
     ③ The third part is the specific address of host resources, such as directory and file name.
The first part and the second part are separated by a ": / /" symbol,
     The second and third parts are separated by "/".
     The first and second parts are indispensable, and the third part can sometimes be omitted.  
For example: https://www.baidu.com/index.html--- Resource access address
From the above example, you may think that URI and URL may have the same concept. In fact, both URI and URL define what resources are, but URL also defines how to access resources. URL is a specific URI, which is a subset of URIs. It not only uniquely identifies a resource, but also provides information to locate the resource. Uri is a semantic abstract concept, which can be absolute or relative, while URL must provide enough information to locate, which is absolute.

6, URL class in java

  Construction method of URL class
     URL(String   spec) form a URL object from the string representation.  
     URL(String   protocol, String   host, int   port, String   file) creates a URL from the specified object protocol, host, port number, and file.  
     Example method
     URLConnection      openConnection() returns a urlconnection instance that represents the URL of the remote object referenced by the URL.  
     InputStream      openStream() opens the URL and returns an InputStream to read from the connection.  
For example: get a graph from a in the network
1. Save the read network resources in the memory output stream (provided that the amount of data is small)

package com.wangxing.test2;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class UrlTest {

	public static void main(String[] args) throws Exception {
//		Construction method of URL class
//		URL(String   spec) form a URL object from the string representation. 
//		URL(String   protocol, String   host, int   port, String   file) creates a URL from the specified object protocol, host, port number, and file. 
		//Create URL object
		String path="https://img14.360buyimg.com/n0/jfs/t1/161275/13/9843/137365/60b59f8eEbade8c1d/3c778f0a77663104.jpg";
		URL url=new URL(path);
		/*Example method
		URLConnection	openConnection() Returns a URLConnection instance that represents the URL of the remote object referenced by the URL. 
		InputStream	openStream() Open the connection to this URL and return an InputStream to read from the connection. */
		//Create a memory output stream object
		ByteArrayOutputStream  out=new ByteArrayOutputStream();
		//Create a byte array that accepts data
		byte[] data=new byte[1024];
		//Create a variable that saves the size of the data each time it is read in
		int temp=0;
		//Create an input stream that opens a connected resource
		InputStream in=url.openStream();
		while((temp=in.read(data))!=-1){
			out.write(data, 0, temp);
		}
		//Create text object and destination address
		String pathname="E:"+File.separator+"wangxingPeiXun"+File.separator+"java back-end"+File.separator+"java Basics"+File.separator+"20211201_22"+File.separator+"Network picture.jpg";
		File file=new File(pathname);
		//Create an output stream object that writes out a file
		FileOutputStream fileout=new FileOutputStream(file);
		//Convert the read from the memory output stream into a byte array for the output stream to read
		fileout.write(out.toByteArray());
		fileout.close();
		out.close();
		in.close();
		
	}
}

  2. Read from the network resource and output it directly to the target file

package com.wangxing.test2;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class UrlTest2 {

	public static void main(String[] args) throws Exception {
//		Construction method of URL class
//		URL(String   spec) form a URL object from the string representation. 
//		URL(String   protocol, String   host, int   port, String   file) creates a URL from the specified object protocol, host, port number, and file. 
		//Create URL object
		String path="https://img14.360buyimg.com/n0/jfs/t1/161275/13/9843/137365/60b59f8eEbade8c1d/3c778f0a77663104.jpg";
		URL url=new URL(path);
		/*Example method
		URLConnection	openConnection() Returns a URLConnection instance that represents the URL of the remote object referenced by the URL. 
		InputStream	openStream() Open the connection to this URL and return an InputStream to read from the connection. */
		//Create text object and destination address
		String pathname="E:"+File.separator+"wangxingPeiXun"+File.separator+"java back-end"+File.separator+"java Basics"+File.separator+"20211201_22"+File.separator+"Network picture 2.jpg";
		File file=new File(pathname);
		//Create an output stream object that writes out a file
		FileOutputStream fileout=new FileOutputStream(file);
		//Create a byte array that accepts data
		byte[] data=new byte[1024];
		//Create a variable that saves the size of the data each time it is read in
		int temp=0;
		//Create an input stream that opens a connected resource
		InputStream in=url.openStream();
		while((temp=in.read(data))!=-1){
			fileout.write(data, 0, temp);
		}
		fileout.close();
		in.close();
		
	}
}

Posted by BraniffNET on Wed, 01 Dec 2021 18:58:37 -0800