Chapter 21 of Java: Network Communication

Network programming basics

        Network programming is about 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 support.

LAN and Internet

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

        The server refers to the computer program that provides information, and the client refers to the computer or program that requests information. The network is used to connect servers and clients to enable mutual communication between the two. However, sometimes it is difficult to distinguish servers from clients within a network. A local area network (LAN) is a group of computers connected in a certain manner. It can consist of two computers or thousands of computers in the same area. Extending a LAN to a larger area becomes a wide area network (WAN). The Internet is made up of countless LANs and WANs.

Network protocol

        The network protocol stipulates the physical, mechanical (connection regulations between the network and the network card), electrical (effective level range) and other characteristics of the connection between computers, the mutual addressing rules between computers, the resolution of data transmission conflicts, and long data How to transmit and receive in segments.

        IP is the abbreviation of Internet Protocol and is a network protocol. The protocol used by the Internet network is TCP/IP protocol. TCP/IP mode 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.

        There are two high-level protocols in the TCP/IP protocol stack, namely Transmission Control Protocol (TCP) and User Datagram Protocol (UDP).

port domain socket

        Generally speaking, a computer has only a single physical connection to the network, so the data read is sent to the specific computer internally and externally through this connection, which is the port. The port in network programming is not a real physical existence, but an imaginary connection device.

        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 just like a socket.

TCP program

        TCP network programming is to use the Socket class to write communication programs. The two applications 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 quite different.

InterAddress class

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

Example: Get the computer’s local name and IP address

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

public class Address {
	public static void main(String[] args) throws java.net.UnknownHostException {
		InetAddress ip;//创建InteAddress对象
		ip=InetAddress.getLocalHost();//实例化对象
		String localname=ip.getHostName();//获取本机名
		String localip=ip.getHostAddress();//获取本机IP地址
		System.out.println("本机名:"+localname);
		System.out.println("本机IP地址:"+localip);
	}

}

operation result:

ServerSocket 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 can wait for the connected socket through the specified port. Server sockets can work with one socket at a time. If multiple clients provide connection requests at the same time, the server socket will store the client requesting the connection in the queue, and then take out a socket from it and connect it to the new socket created by the server. If the number of requested connections is greater than the maximum number, the excess connection requests will be rejected. The default size of the queue is 50.

        The constructor of the ServerSocket class usually throws an IOException, 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 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.

TCP network programming

Example: Create a TCP/IP protocol server. This example is a TCP server program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
	private ServerSocket server;//服务器套接字
	private Socket socket;//客户机套接字
	
	void start() throws IOException {
		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)) {
			    	System.out.println("客户机退出");
			    	break;
				}
				System.out.println("客户机:"+message);
			}
			reader.close();//关闭流
			socket.close();//关闭套接字
		}
	}
	public static void main(String[] args) throws IOException {
		MyServer tcp=new MyServer();
		tcp.start();//启动服务器
	}

}

operation result:

 Run the server-side program, and prompt information will be output, waiting for the customer to call. Let's take a look at the client program.

 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
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();//连接服务器
	}
 
}

operation result:

UDP program

        User Datagram Protocol (UDP) is another form of network information transmission. UDP-based communication and TCP-based communication UDP-based information transfer is faster, but does not provide reliability guarantees. When using UDP to deliver data, the user cannot know whether the data can reach the host correctly, nor can it be sure whether the data reaches the destination in the same order as it was 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 communication based on UDP is as follows:

  • The data is packaged (called a packet) and sent 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 packet socket.
  2. Use DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) to create the
  3. data pack.
  4. Send packets using the send() method of the DatagramSocket class.

        The steps for receiving data packets are as follows:

  1. Use DatagramSocket(int port) to create a packet socket bound to the specified port.
  2. Use DatagramPacket(byte[]buf,int length) to create a byte array to receive the packet.
  3. Use the receive() 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).

         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 data packet, but also specifies the target address and port of the data packet. When sending data, the Socket address and port number of the receiver must be specified, so the second construction method is used. DamgramPacket objects can be created to send data.

DatagramSocket class

        The DatagramSocket class in the javanet 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 constructor creates a DatagramSocket object, creates a datagram socket, and binds it to the specified port on the local host. The third constructor 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.​ 

UDP network programming

Example: Create a UDP protocol radio station program, and the broadcast host program continuously broadcasts information to the outside world.

 
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
 
public class Notification extends Thread{
	String weather = "节日预报:八点有大型晚会,请收听";//发送的消息
	int port = 9898;//端口
	InetAddress iaddress = null;
	MulticastSocket socket = null;//多点广播套接字
	
	Notification(){
		try {
			iaddress = InetAddress.getByName("224.225.10.0");//广播组地址
			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();//启动线程
	}
 
}

operation result:

Receive broadcast program. code show as below:

 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
 
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();
		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.225.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();//输出异常信息
			}
		}
	}
 
	@Override
	public void actionPerformed(ActionEvent e) {	//单击按钮ince触发的事件
		if(e.getSource() == inceBtn) {
		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);
	}
 
}

operation result:

        

Je suppose que tu aimes

Origine blog.csdn.net/nmy15570188135/article/details/134792983
conseillé
Classement