Chapter 21 Network Communication

Table of contents

Network programming basics 

LAN and Internet

 Network protocol

1.IP protocol

2. TCP and UDP protocols

Ports and Sockets

TCP program

InetAddress class

ServerSocket class

TCP network programming

UDP program

DatagramPacket class

DatagramSocker class

UDP network programming


 

Network programming basics 

LAN and Internet

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

 Network protocol

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 by the network. This address is the I address. So far, the I address is represented by 4 bytes, which is a 32-bit binary number, called IPv4. For ease of use, the decimal number of each byte is usually taken, and each byte is separated by a dot to represent the I address, such as 192.168.1.1. Now people are experimenting with using 16 bytes to represent the I address, which is IPv6, but IPv6 has not yet been put into use.

The TCP/IP model is a hierarchical structure, divided into 4 layers, namely application layer, transport layer, Internet layer and network layer. Each layer implements specific functions, provides specific services and access interfaces, and is relatively independent, as shown in the figure.

2. TCP and UDP protocols

In the TCPAIP 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 wire-based protocol that provides reliable data transfer 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, Telnet, etc. all require the use of 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.

Ports and Sockets

Generally speaking, a computer has only a single physical connection to the network (Physical Connection), 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 the figure.

Usually, 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 conflicting with ports used by another application or system service.

Sockets in network programs are used to connect applications to ports. A socket is an imaginary connecting device that connects electrical appliances and wires like a socket, as shown in the figure.

Java abstracts sockets into classes, and programmers only need to create Socket class objects to use sockets.

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. The interaction process between the server and the client is shown in the figure.

 

The server program creates a ServerSocket (server-side socket) object, calls the accept0 method and waits for the client to connect
The client program creates a Socket object and requests to establish a connection with the server< /span>
The server receives the client's connection request and creates a new Socket object to establish a connection with the client. The server then continues to wait for new requests

InetAddress class

The InetAddress class in the java.net package is a class related to IP addresses. You can use this class to obtain information such as IP addresses and host addresses.

 Example 21.1

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

The running results are as follows:

ServerSocket class

The construction method of the ServerSocker class usually throws 1OException, which has the following forms:
ServerSocket(): Creates an unbound server socket.
ServerSocket(int port): Creates 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): Creates 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 I addresses on the computer. The user can clearly specify which network card or IP address ServerSocket waits for the client's connection request on.
The common methods of the ServerSocket class are shown in Table 21.2.

TCP network programming

Example 21.2

 
 
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.2

 The running results are as follows:

Write a client program to send the information entered by the user in the text box to the server, and display the information entered in the text box in the client's text field.

 
 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.Socket;
import javax.swing.*;
 
public class MyClient extends JFrame {
	private PrintWriter writer;// 根据套接字字节流创建的字符输出流
	Socket socket; // 客户端套接字
	private JTextArea area = new JTextArea();// 展示信息的文本域
	private JTextField text = new JTextField(); // 发送信息的文本框
 
	public MyClient() {
		setTitle("向服务器送数据");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane(); // 主容器
		JScrollPane scrollPane = new JScrollPane(area);// 滚动面板
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		c.add(text, "South"); // 将文本框放在窗体的下部
		text.addActionListener(new ActionListener() {// 文本框触发回车事件
			public void actionPerformed(ActionEvent e) {
				writer.println(text.getText().trim()); // 将文本框中的信息写入流
				area.append(text.getText() + '\n'); // 将文本框中的信息显示在文本域中
				text.setText(""); // 将文本框清空
			}
		});
	}
 
	private void connect() { // 连接服务器方法
		area.append("尝试连接\n"); // 文本域中提示信息
		try {
			socket = new Socket("127.0.0.1", 8998); // 连接本地计算机的8998端口
			writer = new PrintWriter(socket.getOutputStream(), true);
			area.append("完成连接\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
	public static void main(String[] args) {
		MyClient clien = new MyClient();
		clien.setSize(200, 200); // 窗体大小
		clien.setVisible(true); // 显示窗体
		clien.connect(); // 连接服务器
	}
}
//21.2

The running results are as follows:

UDP program

The basic mode based on UDP communication is as follows:

packages the data (called a data packet) and then sends the data packet to the destination.
Receive data packets sent by others, and then view the data packets.
The steps to send a data packet are as follows:

(1) Use DatagramSocketO to create a 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 sendO method of the DatagramSocket class to send the data packet.

The steps to receive a 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 receive0 method of the DatagramPacket class to receive UDP packets.

DatagramPacket class

The DatagramPacket class of the java.net package is used to represent data packets. The construction method of the DatagramPacket class is as follows:

DatagramPacket(byte[] buf, int length)
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
First This constructor 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.

DatagramSocker class

() in java.net package
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 I addresses.

UDP network programming

Example 21.3

1. The broadcast host program continuously broadcasts information to the outside world. The code is as follows:

 
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(); // 启动线程
	}
}
//21.3

 The running results are as follows:

2. Receive broadcast program. Press the "Start Receive" button on a single machine and the system will start receiving the information broadcast by the host; press the "Stop Receive" button on a single machine and the system will stop receiving the information broadcast by the broadcast host. code show as below:

 
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;
import javax.swing.*;
 
public class Receive extends JFrame implements Runnable, ActionListener {
	int port; // 端口
	InetAddress group = null; // 广播组地址
	MulticastSocket socket = null; // 多点广播套接字对象
	JButton inceBtn = new JButton("开始接收");
	JButton stopBtn = new JButton("停止接收");
	JTextArea inceAr = new JTextArea(10, 10); // 显示接收广播的文本域
	JTextArea inced = new JTextArea(10, 10);
	Thread thread;
	boolean stop = false; // 停止接受信息状态
 
	public Receive() {
		setTitle("广播数据报");
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		thread = new Thread(this);
		inceBtn.addActionListener(this); // 绑定按钮ince的单击事件
		stopBtn.addActionListener(this); // 绑定按钮stop的单击事件
		inceAr.setForeground(Color.blue); // 指定文本域中文字的颜色
		JPanel north = new JPanel(); // 创建Jpanel对象
		north.add(inceBtn); // 将按钮添加到面板north上
		north.add(stopBtn);
		add(north, BorderLayout.NORTH); // 将north放置在窗体的上部
		JPanel center = new JPanel(); // 创建面板对象center
		center.setLayout(new GridLayout(1, 2)); // 设置面板布局
		center.add(inceAr); // 将文本域添加到面板上
		center.add(inced);
		add(center, BorderLayout.CENTER); // 设置面板布局
		validate(); // 刷新
		port = 9898; // 设置端口号
		try {
			group = InetAddress.getByName("224.255.10.0"); // 指定接收地址
			socket = new MulticastSocket(port); // 绑定多点广播套接字
			socket.joinGroup(group); // 加入广播组
		} catch (IOException e) {
			e.printStackTrace(); // 输出异常信息
		}
		setBounds(100, 50, 360, 380); // 设置布局
		setVisible(true); // 将窗体设置为显示状态
	}
 
	public void run() { // run()方法
		while (!stop) {
			byte data[] = new byte[1024]; // 创建缓存字节数组
			DatagramPacket packet = null;
			packet = new DatagramPacket(data, data.length, group, port); // 待接收的数据包
			try {
				socket.receive(packet); // 接收数据包
				String message = new String(packet.getData(), 0, packet.getLength()); // 获取数据包中的内容
				inceAr.setText("正在接收的内容:\n" + message); // 将接收内容显示在文本域中
				inced.append(message + "\n"); // 每条信息为一行
			} catch (IOException e) {
				e.printStackTrace(); // 输出异常信息
			}
		}
	}
 
	public void actionPerformed(ActionEvent e) { // 单击事件
		if (e.getSource() == inceBtn) { // 单击按钮ince触发的事件
			inceBtn.setBackground(Color.red); // 设置按钮颜色
			stopBtn.setBackground(Color.yellow);
			if (!(thread.isAlive())) { // 如线程不处于“新建状态”
				thread = new Thread(this); // 实例化Thread对象
			}
			thread.start(); // 启动线程
			stop = false; // 开始接受信息
		}
		if (e.getSource() == stopBtn) { // 单击按钮stop触发的事件
			inceBtn.setBackground(Color.yellow); // 设置按钮颜色
			stopBtn.setBackground(Color.red);
			stop = true; // 停止接受信息
		}
	}
 
	public static void main(String[] args) {
		Receive rec = new Receive();
		rec.setSize(460, 200);
	}
}

 The running results are as follows:

 

Guess you like

Origin blog.csdn.net/2301_76549195/article/details/134876042