java study notes - network programming

1. Introduction to Network Programming

Network programming: Under the network communication protocol, data exchange can be performed between programs running on different computers that realize network interconnection

1.1, three elements of network programming

IP address: In order for computers in the network to communicate with each other, each computer must be assigned an identification number, which is used to specify the computer to receive data and identify the computer that sends it, and the ip address is this identification number, also It is the identification
port of the device: the communication of the network is essentially the communication of two applications. Each computer has many applications, so how to distinguish these applications in network communication? If the IP address can uniquely identify the device in the network, then the port number can uniquely identify the application in the device. That is, the identification protocol of the application
: multiple computers can be connected through a computer network. Computers in the same network need to abide by certain rules when connecting and communicating, just like a neutral-colored car on the road. Just follow the traffic rules. In a computer network, these rules of connection and communication are called network communication protocols, which make uniform regulations on the transmission format, transmission rate, and transmission steps of data, and both parties must abide by them to complete data exchange. Common protocols are UDP protocol and TCP protocol.

1.2, IP address: is the unique identification of the device in the network

IP addresses are divided into two categories: IPv4 IPv6
common commands:
ipconfig: check the local IP address
ping IP address: check whether the network is connected
Special IP address:
127.0.0.1: is the loopback address, which can represent the local address, generally used for testing

1.3, the use of InetAddress

In order to facilitate our acquisition and operation of IP addresses, Jaca provides a class InetAddress for us to use
InetAddress: This class identifies the Internet Protocol (IP) address
static InetAddress getByName(String host): Determines the IP address of the host name. The host name can be a machine name or an IP address
String getHostName(): Get the host name of this IP address
String getHostAddress(): Return the IP address string in the text display

1.4, port, protocol

Port: The unique identification port number of the application on the device
: an integer represented by two bytes, its value range is 0-65535. The port number between 0-1023 is used for some well-known network services and applications, Ordinary applications need to use port numbers above 1024.
Protocol: In computer networks, the rules for connection and communication are called network communication protocols
. UDP Protocol: User Datagram Protocol, is a connectionless communication protocol. Due to the low consumption of resources and high communication efficiency using the UDP protocol, all are usually used for the transmission of audio, video and general data. However, it is not recommended to use the UDP protocol TCP protocol when transmitting important data
: Transmission Control Protocol is a connection-oriented communication protocol, that is, before transmitting data, a logical connection is established between the sender and the receiver, and then the data is transmitted. It provides two Reliable and error-free data transfer between computers. In the TCP connection, it is necessary to clarify the client and the server, and the client sends a connection request to the server. The creation of each connection requires a "three-way handshake"
three-way handshake: in the TCP protocol, in the preparation stage for sending data, the client Three interactions between the client and the server to ensure the reliability of the connection The
first handshake, the client sends a connection request to the server, waits for the server to confirm
the second handshake, and the server sends a response back to the client, notifying the client that it has received Connection request
The third handshake, the client sends confirmation information to the server again to confirm that the connection
has completed the three-way handshake. After the connection is established, the client and the server can start data transmission. Due to this connection-oriented feature, the TCP protocol can guarantee the security of transmitted data.

2. UDP communication program

2.1, UDP communication principle

The UDP protocol is an unreliable network protocol. It establishes a Socket object at both ends of the communication, but these two Sockets are only objects for sending and receiving data. Therefore, there is no so-called communication between the two parties based on the UDP protocol. The concept of client and server
JAVA provides the DaragramSocket class as a UDP-based Socket
to send data steps:
1. Create a Socket object (DatagranmSocket) on the sender side
2. Create data and pack the data DategramPacket(byte[] buf,int length ,InetAddress address,int port)
3. Call the method of the DatagramSocket object to send data: void send(DatagramSocket p);
4. Close the sender: void close();
Steps to receive data:
1. Create a Socket object (DaragramSocket) of the receiver : DatagramSocket(int port)
2. Create a data packet for receiving data: DatagramPacket(byte[] buf, int length)
3. Call the method of the DatagramSocket object to receive data: void receive(DatagramPacket p)
4. Parse the data packet, And display the data in the console: byte[] getData(); int getLength();
5. Close the receiving end

2.2, UDP communication program practice

UDP send data: The data comes from the keyboard input, until the input data is 886, the sending data ends
UDP receive data: Because the receiver does not know when the sender stops sending, it adopts an infinite loop to receive

package UDP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class SendDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		
		DatagramSocket ds = new DatagramSocket();
		
		System.out.println("输入:");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while((line = br.readLine()) != null) {
    
    
			if("886".equals(line)) {
    
    
				break;
			}
			
			byte[] bys = line.getBytes();
			DatagramPacket dp = new DatagramPacket(bys,bys.length,InetAddress.getByName("192.168.2.225"),12345);
			
			ds.send(dp);
		}
		
		ds.close();
		
	}
}
package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class ReveiveDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		DatagramSocket ds = new DatagramSocket(12345);
		
		
		while(true) {
    
    
			
		
			byte[] bys=  new byte[1024];
			DatagramPacket dp = new DatagramPacket(bys,bys.length);
			
			ds.receive(dp);
			
			System.out.println("数据是:"+new String(dp.getData(),0,dp.getLength()));
			
			
		}
		
	}
}

3. TCP communication program

3.1, TCP communication principle

The TCP communication protocol is a reliable network protocol. It establishes a Socket object at both ends of the communication, thereby forming a network virtual link at both ends of the communication. Once the virtual network link is established, the programs at both ends can pass virtual link for communication.
Java provides a good encapsulation for the network based on the TCP protocol. It uses Socket objects to represent the communication ports at both ends, and generates IO streams through Socket for network communication.
Java provides the Socket class for the client and the ServerSocket class for the server to
send Data steps:
1. Create a client's Socket object (Socket): Socket(String host, int port)
2. Get the output stream, write data: OutputStream getOutputStream()
3. Release resources: void close();
Steps to receive data :
1. Create a server-side Socket object (ServerSocket): ServerSocket (int port)
2. Monitor the client connection and return a Socket object: Socket accept();
3. Get the input stream, read the data, and display the data on the console :InputStream getInputStream()
4. Release resources: void close();

3.2, TCP case

package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClienDemo {
    
    
	public static void main(String[] args) throws UnknownHostException, IOException {
    
    
		
		//创建客户端的Socket对象
		Socket s = new Socket("192.168.2.225",10000);
		
		//获取输出流,写数据
		OutputStream os = s.getOutputStream();
		os.write("hello,我来了".getBytes());
		
		//接收服务器反馈
		InputStream is = s.getInputStream();
		byte[] bys = new byte[1024];
		int len = is.read(bys);
		String data = new String(bys,0,len);
		System.out.println("客户端:"+data);
		
		//释放资源
		s.close();
		
	}
}
package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		
		//创建服务器端的Socket对象
		ServerSocket ss = new ServerSocket(10000);
		
		//监听客户端连接,返回一个Socket对象
		Socket s = ss.accept();
		
		//获取输入流,读数据,并把数据显示在控制台
		InputStream is = s.getInputStream();
		byte[] bys = new byte[1024];
		int len = is.read(bys);
		String data = new String(bys,0,len);
		System.out.println("服务器:"+data);
		
		//给出反馈
		OutputStream os = s.getOutputStream();
		os.write("数据已经收到".getBytes());
		
		//释放资源
		ss.close();
	}
}

Guess you like

Origin blog.csdn.net/weixin_45573296/article/details/123107569