Chapter 21 Summary Network Communication

21.1 Basics of Network Programming

Network programming is writing programs that communicate with other computers. Java has encapsulated the elements required by network programs into different classes. As long as users create objects of these classes and use corresponding methods, they can write high-quality network communication programs even if they do not have relevant network knowledge.

21.1.1 LAN and Internet

In order to achieve communication between two computers, a network line must be used to connect the two computers.

21.1.2 Network protocols

The network protocol stipulates the physical, mechanical (connection regulations of network cables and network cards), electrical (effective level range) and other characteristics of the connection between computers, the mutual addressing rules between computers, and the reasons for data transmission conflicts. Solution, how to transmit and receive long data in segments, etc. Just like different countries have different laws, there are currently a variety of network protocols. Below is a brief introduction to several commonly used network protocols.
1.IP protocol

IP is the abbreviation of Internet Protocol, which is a network protocol. The protocol used by the Internet network is the TCP/IP protocol, whose full name is Transmission Control Protocol/Internet Protocol. The Internet relies on the TCP/IP protocol to realize interconnection between different hardware structures, different operating systems, and different network systems on a global scale. There are hundreds of millions of hosts on the Internet network, and each host represents itself with an Internet address assigned to it by the network. This address is an IP address.

The TCP/IP model is a hierarchical structure, divided into four layers. Each layer implements specific functions and provides specific services and access interfaces.

2.TCP and UDP protocols

In the TCP/IP protocol stack, there are two high-level protocols that network application writers should understand, namely Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) ).
The TCP protocol is a protocol based on fixed connections that provides reliable data transmission between two computers. TCP can ensure that when data is sent from one end to the other end of the connection, it is actually delivered, and that the arriving data is arranged in the same order as when it was sent. Therefore, the TCP protocol is suitable for situations with relatively high reliability requirements. Just like making a phone call, you must first dial the number to the other party. After the two ends are connected, you can hear each other's words and know what the other party is responding to.
HTTP, FTP and Telnet all require reliable communication channels. For example, when HTTP reads data from a URL, if the order of the data received is different from that when sent, a confusing HTML file or some invalid information may appear.
UDP is a connectionless communication protocol that does not guarantee reliable transmission of data, but it can send data to several targets or receive data from several sources. UDP works by sending packets independently. This method is like a postman delivering letters to the recipient. You can send many letters to the same person, and each letter is relatively independent. The order in which the letters are delivered is not important, nor is the order in which the recipient receives the letters. Guaranteed to be in the same order as the letters were sent.
The UDP protocol is suitable for some websites that do not have high requirements for data accuracy, but have very high requirements for transmission speed and timeliness, such as online chat rooms, online videos, etc. This is because the TCP protocol has additional costs in authentication, which may slow down the transmission speed. However, even if a small part of the data packets in the UDP protocol are lost or the transmission order is different, it will not seriously affect the communication.
Note that some firewalls and routers are set to not allow UDP packet transmission. Therefore, if you encounter UDP connection problems, you should first determine whether the UDP protocol is allowed on your network.

21.1.3 Ports and Sockets

Generally speaking, a computer has only a single physical connection (PhysicalConnection) to the network, and all data is sent to the specific computer internally and externally through this connection. This is the port. The port in network programming is not a real physical existence, but an imaginary connection device. The port is specified as an integer between 0 and 65535. HTTP service generally uses port 80, and FTP service uses port 21. If a computer provides multiple services such as HTTP and FTP, the client will use different ports to determine which service of the server to connect to, as shown in Figure 21.3.
Generally, port numbers from 0 to 1023 are used for some well-known network services and applications. Users’ ordinary network applications should use port numbers above 1024 to avoid port numbers that are inconsistent with another application or application. The port used by the system service conflicts.
Sockets in network programs are used to connect applications to ports. A socket is an imaginary connecting device that can connect electrical appliances and wires like a socket, as shown in Figure 21.4. Java abstracts sockets into classes, and programmers only need to create Socket class objects to use sockets.

21.2 TCP program

TCP network programming refers to writing communication programs using the Socket class. The two application programs that use the TCP protocol to communicate are divided into primary and secondary applications. One is called the server program and the other is called the client program. The functions and writing methods of the two are very different.

 

21.2.1InetAddress class

The InetAddress class in the jae package is a class related to IP addresses. This class can be used to obtain information such as IP addresses and host addresses.

 

import java.net.*; 									//导入java.net包
public class Address { 								//创建类
	public static void main(String[] args) {
		InetAddress ip; 							//创建InetAddress对象
		try { 									//使用try语句块捕捉可能出现的异常
			ip = InetAddress.getLocalHost(); 			//实例化对象
			String localname = ip.getHostName(); 		//获取本机名
			String localip = ip.getHostAddress(); 		//获取本机IP地址
			System.out.println("本机名:" + localname);	//将本机名输出
			System.out.println("本机IP地址:" + localip); 	//将本机IP地址输出
		} catch (UnknownHostException e) {
			e.printStackTrace(); 						//输出异常信息
		}
	}
}

 

21.2.2SeverSockt class

The ServerSocket class in the java.net package is used to represent a server socket. Its main function is to wait for "requests" from the network.
It waits for a connected socket on the specified port. Server sockets can be connected to one socket at a time. If multiple clients make connection requests at the same time, the server socket will queue the client requesting the connection and then remove a socket from it. Connect to the server's newly created socket. If the number of requested connections is greater than the maximum number, the excess connection requests will be rejected. The default size is 50.
The constructor of the ServerSocket class usually throws an IOException, which has the following forms:
☑ ServerSocket(): Create an unbound server socket .    
☑ ServerSocket(int port): Create a server socket bound to a specific port.
☑ ServerSocket(int port, int backlog): Create a server socket using the specified backlog and bind it to the specified local port number.
☑ ServerSocket(int port, int backlog, InetAddress bindAddress): Create a server with the specified port, listening backlog, and local IP address to bind to. This situation applies to situations where there are multiple network cards and multiple IP addresses on the computer. The user can clearly specify which network card or IP address ServerSocket waits for the client's connection request on. Common methods of the ServerSocket class are shown in Table 21.2.

Calling the accept() method of the ServerSocket class will return a Socket object connected to the client's Socket object. The output stream obtained by the server-side Socket object using the getOutputStream() method will point to the input stream obtained by the client-side Socket object using the getinputStream() method; similarly, the input stream obtained by the server-side Socket object using the getlnputStream() method will point to the client The output stream obtained by the end Socket object using the getOutputStream() method. That is, when the server writes information to the output stream, the client can read it through the corresponding input stream, and vice versa.​ 

21.2.3TCP network programming

What about TCP communication? The main communication method is one-to-one communication, which also has advantages and disadvantages. Its advantage is that it is more reliable than UDP because its communication method requires sending a message first to see if the client can receive it. If there is no reply to the message, the server will not send a file and wait for the client to reply to the message. This handshake mode will be very reliable. The following code explains:
 

import java.io.*;
import java.net.*;

public class MyServer {
	private ServerSocket server; // 服务器套接字
	private Socket socket; // 客户端套接字

	void start() {// 启动服务器
		try {
			server = new ServerSocket(8998); // 服务器启用8998端口
			System.out.println("服务器套接字已经创建成功");
			while (true) {
				System.out.println("等待客户端的连接");
				socket = server.accept(); // 服务器监听客户端连接
				// 根据套接字字节流创建字符输入流
				BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				while (true) {// 循环接受信息
					String message = reader.readLine();// 读取一行文本
					if ("exit".equals(message)) {// 如果客户端发来的内容为“exit”
						System.out.println("客户端退出");
						break;// 停止接受信息
					}
					System.out.println("客户端:" + message);
				}
				reader.close(); // 关闭流
				socket.close(); // 关闭套接字
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		MyServer tcp = new MyServer();
		tcp.start(); // 启动服务器
	}
}

 

21.3 UPD procedures

User Datagram Protocol (UDP) is another form of network information transmission. UDP-based communication is different from TCP-based communication. UDP-based information transfer is faster, but does not provide reliability guarantees. When using UDP to transmit data, users cannot know whether the data can reach the host correctly, nor can they be sure whether the order arriving at the destination is the same as the order sent. Although UDP is an unreliable protocol, if you need to transfer information quickly and can tolerate small errors, you can consider using UDP.
The basic mode of UDP-based communication is as follows:
☑Package the data (called a data packet), and then send the data packet to the destination.

☑Receive data packets sent by others, and then view the data packets.

The steps for sending a data packet are as follows:
(1) Use DatagramSocket() to create a data packet socket.
(2) Use DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) to create the data packet to be sent.
(3) Use the send() method of the DatagramSocket class to send the data packet.

The steps to receive a data packet are as follows:

(1) Use DatagramSocket(int port) to create a data packet socket and bind it to the specified port.

(2) Use DatagramPacket(byte[] buf, int length) to create a byte array to receive the data packet.

(3) Use the receive( method of the DatagramPacket class to receive UDP packets.
Note

When the receive() method of the DatagramSocket class receives data, if there is no data that can be received, the receive() method will block under normal circumstances and wait until data is transmitted from the network. The receive() method receives the data and returns. If no data is sent over the network and the receive() method is not blocked, there must be a problem with the program. In most cases, it is because a port number is used that is occupied by other programs.

21.3.1DatagramPacket class

The DatagramPacket class of the avanet package is used to represent data packets. The construction method of the DatagramPacket class is as follows: ☑DatagramPacke1(byte]buf, int length).
☑DatagramPackel(byse[] buf,int length,InetAddress address, int port).< a i=2> The first construction method specifies the memory space and size of the data packet when creating the DatagramPacket object. The second construction method not only specifies the memory space and size of the packet, but also specifies the destination address and port of the packet. When sending data, you must specify the Socket address and port number of the receiver, so use the second construction method to create a DatagramPacket object for sending data.

21.3.2DatagramSocket class

The DatagramSocket class in the java.net package is used to represent a socket for sending and receiving data packets. The construction method of this class is as follows: ☑DatagramSocket().
☑DatagramSocket(int port).
☑DatagramSocket(int port, InetAddress addr).
The first construction method creates a DatagramSocket object, constructs a datagram socket, and binds it to any available port on the local host. The second construction method creates a DatagramSocket object, creates a datagram socket, and binds it to the specified port on the local host. The third construction method creates a DatagramSocket object, creates a datagram socket, and binds it to the specified port and the specified local address. The third constructor is suitable for situations where there are multiple network cards and multiple IP addresses.

The most important ones are TCP and UDP. The main difference between them is that one is one-to-one communication and the other is one-to-many communication. Of course, both have their own advantages and disadvantages. Next, we will explain the TCP part first.

21.3.3UPD network programming

Create a broadcast datagram program below

import java.io.IOException;
import java.net.*;

public class Notification extends Thread {
	String weather = "节目预报:八点有大型晚会,请收听";// 发送的消息
	int port = 9898; // 端口
	InetAddress iaddress = null;
	MulticastSocket socket = null; // 多点广播套接字

	Notification() {
		try {
			iaddress = InetAddress.getByName("224.255.10.0"); // 实例化InetAddress,指定地址
			socket = new MulticastSocket(port); // 实例化多点广播套接字
			socket.setTimeToLive(1); // 指定发送范围是本地网络
			socket.joinGroup(iaddress); // 加入广播组
		} catch (IOException e) {
			e.printStackTrace(); // 输出异常信息
		}
	}

	public void run() {
		while (true) {
			DatagramPacket packet = null; // 数据包
			byte data[] = weather.getBytes(); // 字符串消息的字节数组
			packet = new DatagramPacket(data, data.length, iaddress, port); // 将数据打包
			System.out.println(weather); // 控制台打印消息
			try {
				socket.send(packet); // 发送数据
				sleep(3000); // 线程休眠
			} catch (IOException e) {
				e.printStackTrace(); 
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) { 
		Notification w = new Notification();
		w.start(); // 启动线程
	}
}

Guess you like

Origin blog.csdn.net/Leonie1/article/details/134823194