Java Basics 22 Network Programming (HTTP and UDP)

Like you who love programming!
Learn SpringBoot actual combat course https://edu.csdn.net/course/detail/31433
Learn SpringCloud introductory course https://edu.csdn.net/course/detail/31451


Preface

Network programming is also a good game of Java. This article takes you to understand the related concepts of the network, and then realize the network communication of HTTP and UDP.

Network related concepts

Network programming refers to data communication between different computers in the same network

computer network

Computer network is a large-scale and powerful network system that connects computers distributed in different areas and specialized external equipment with communication lines, so that computers can transfer information to each other and share data, software and other resources.

Computer networks are divided into geographical locations:

  • local area network
  • Metropolitan Area Network
  • Wan

IP address

The IP address refers to the Internet address (Internet Protocol Address, which is the unique identifier between the networked device and the Internet. In the same network segment, the IP address is the only one. The
IP address is numeric and is a 32-bit binary. Divide it into 4 8-bit binary numbers, separated by dots between each 8-bit integer, each 8-bit integer can be converted to a decimal integer from 0 to 255, for example: 202.9.128.88

IP address classification

  • Category A: reserved for government structures, 1.0.0.1 ~ 126.255.255.254
  • Category B: allocated to medium-sized enterprises, 128.0.0.1 ~ 191.255.255.254
  • Category C: Assigned to any individual in need, 192.0.0.1 ~ 223.255.255.254
  • Class D: used for multicast, 224.0.0.1 ~ 239.255.255.254
  • Class E: for experiment, 240.0.0.1 ~ 255.255.255.254
  • Recovery address: 127.0.0.1, refers to the local machine, generally used for testing

port

The IP address can uniquely identify a communication entity on the network, but a communication entity can have multiple communication programs providing network services at the same time, and the port is also required

Both sending and receiving data need to enter and exit the computer through the port. The port number is used to uniquely identify the program for network communication on the communication entity. Two programs on the same machine cannot occupy the same port.

The value range of the port number: 0 ~ 65535

Port classification:

  • Recognized port: 0~1023
  • Registered port: 1025~49151
  • Dynamic or private port: 1024~65535

Common ports:

  • mysql:3306
  • oracle:1521
  • tomcat:8080
  • Browser: 80

letter of agreement

Network communication protocol
is a collection of rules that must be observed when exchanging information between peer entities communicating with each other in a computer network.

The network is divided into 7 layers.
Insert picture description here
Commonly used communication protocols:

  • Transport layer protocol: TCP, UDP, etc.
  • Network layer protocol: IPV4, IPV6, etc.
  • Application layer protocol: HTTP, FTP, SMTP, POP3, etc.

HTTP protocol

Hyper Text Transfer Protocol (Hyper Text Transfer Protocol) is used to standardize the transmission of text data in the network. It is an application layer protocol, and the bottom layer is based on the TCP/IP protocol.

Features of HTTP protocol

  1. Simple and fast
  2. Support communication between client and server
  3. No connection, once the client finishes accessing, the connection with the server will be disconnected
  4. Stateless, the server will not keep the client's data
  5. In the request and response mode, the client sends a request to the server, and the server sends a response to the browser.
    Insert picture description here

HTTP request method

  • GET data will be included in the URL, which is not safe and has restrictions on the length of the data, suitable for query and search
  • POST data is sent in the background, which is more secure, has no limitation on the data length, and is suitable for sending sensitive data
  • PUT update server resources
  • DELETE request to delete a resource
  • TRACE tracking server information
  • OPTIONS allows to view server performance
  • HEAD is used to get the header
  • CONNECT changes the connection to a pipe proxy server

HTTP response code

The server tells the browser the response result

Code Description
1xx messages The request has been received by the server, continue processing
2xx success The request has been successfully received, understood, and accepted by the server
3xx redirect Need follow-up action to complete this request
4xx request error The request contains a lexical error or cannot be executed
5xx server error The server encountered an error while processing a correct request

Common response codes:

Code Description
200 OK request succeeded
400 Bad Request request has syntax error
401 Unauthorized request is not authorized
403 Forbidden server refuses to provide service
404 Not Found The requested resource does not exist
500 Internal Server Error An error occurred in the server
503 Server Unavailable The server cannot handle

HTTP network connection

Main API:

  • URL resource address
  • HttpURLConnection network connection

URL
Uniform Resource Locator (Uniform Resource Locator) is a representation method used to specify the location of information on the Internet.

Creation method

URL url = new URL("资源的地址");

Main method

  • URLConnection openConnection() opens a network connection

HttpURLConnection

Main method

method effect
void disconnect() Close the connection
setRequestMethod(String method) Set request method
int getResponseCode() Return response code
void setConnectTimeout(long time) Set connection timeout
void setRequestProperty(String key,String value) Set request header attributes
InputStream getInputStream() Get input stream
OutputStream getOutputStream() Get output stream
void setDoOutput(boolean output) Set whether to send data
long getContentLength() Get the length of the resource

Case: Download pictures from the Internet

  1. Create a URL object and pass in the address of the network file
  2. Call openConnection to open the connection and get the HttpURLConnection object
  3. Set various properties of the connection
  4. Call getInputStream to get the input stream
  5. Create file output stream
  6. Read data from the network input stream and write to the file output stream
  7. Close the connection
public class DownloadTest {

	/**
	 * 下载文件
	 * @param urlStr  资源的地址
	 * @param savePath 保存的路径
	 */
	public static void download(String urlStr,String savePath){
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(3000); //连接超时
			conn.setRequestMethod("GET"); 
			System.out.println("文件长度是:"+conn.getContentLength());
			if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){				
				try(
					InputStream	in = conn.getInputStream();
					OutputStream out = new FileOutputStream(savePath);){
					byte[] buffer = new byte[1024];
					int len = 0;
					while((len = in.read(buffer)) != -1){
						out.write(buffer, 0, len);
					}
					System.out.println("文件下载完毕");
					Runtime.getRuntime().exec("mspaint "+savePath); //用画图打开
				}catch(IOException ex){
					ex.printStackTrace();
				}
			}
			conn.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	public static void main(String[] args) {
		download("http://hbimg.b0.upaiyun.com/a09289289df694cd6157f997ffa017cc44d4ca9e288fb-OehMYA_fw658",
				"D:\\mm.jpg");
	}
	
}

Insert picture description here

UDP programming

UDP is a datagram protocol, similar to broadcasting. It does not need a three-way handshake to create a connection. The data transmission speed is fast but unreliable

Application scenarios: voice, video chat

DatagramSocket

DatagramSocket can be used as UDP client or server

Creation method:

服务器端
new DatagramSocket(端口号)	
客户端
new DatagramSocket()	  

Main method:

  • send(DatagramPacket) send data packet
  • receive(DatagramPacket) receive data packet

DatagramPacket

DatagramPacket is a UDP data packet, used to receive and send data

Creation method:

用于接收数据的数据包
DatagramPacket(byte[] 数据字节 ,int 数据长度)
用于发送数据的数据包
DatagramPacket(byte[] 数据字节 ,int 数据长度,InetAddress 地址,int 端口)

Common methods:

  • byte[] getData() get data

UDP communication

Use UDP to send simple messages

UDP server side

public class UDPServer {

	public static final int PORT = 8888;
	
	public void start(){
		System.out.println("server started!");
		try {
			//创建UDP服务端
			DatagramSocket server = new DatagramSocket(PORT);
			//创建数据包
			byte[] buf = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buf, buf.length);
			//接收数据包
			server.receive(packet);
			String str = new String(packet.getData());
			System.out.println("收到消息:" + str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new UDPServer().start();
	}

}

UDP client

public class UDPClient {

	public void sendMsg(String ip,int port,String msg){
		try {
			//创建UDP客户端
			DatagramSocket client = new DatagramSocket();
			//创建数据包
			byte[] buf = msg.getBytes();
			DatagramPacket packet = new DatagramPacket(buf,buf.length,InetAddress.getByName(ip),port);
			//发送数据包
			client.send(packet);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new UDPClient().sendMsg("127.0.0.1", 8888, "Hello UDP!");
	}
}

End


If you need to learn other Java knowledge, poke here ultra-detailed knowledge of Java Summary

Guess you like

Origin blog.csdn.net/u013343114/article/details/112798898