java learning notes - network programming

Posted by austrainer on Thu, 24 Feb 2022 14:07:00 +0100

1, Introduction to network programming

Network programming: under the network communication protocol, data can be exchanged between programs running on different computers to realize network interconnection

1.1 three elements of network programming

IP address: to enable computers in the network to communicate with each other, you must specify an identification number for each computer. Through this identification number, you can specify the computer to receive data and identify the computer to send. The IP address is this identification number, that is, the identification of the device
Port: network communication is essentially the communication between 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, the port number can uniquely identify the application in the device. That is, the identity of the application
Protocol: multiple computers can be connected through the computer network. Computers located in the same network need to abide by certain rules when connecting and communicating, just as neutral cars on the road must abide by traffic rules. In the computer network, these rules of connection and communication are called network communication protocol. It makes unified provisions on the transmission format, transmission rate and transmission steps of data. Both sides of communication must abide by them at the same time to complete the data exchange. The common protocols are UDP and TCP.

1.2. IP address: it is the unique identification of the equipment in the network

IP addresses fall into two categories: IPv4 and IPv6
Common commands:
ipconfig: view the local IP address
ping IP address: check whether the network is connected
Special IP address:
127.0.0.1: it is the loopback address, which can represent the local address. It is generally used for testing

1.3 use of InetAddress

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

1.4 port and protocol

Port: the unique identification of the application on the device
Port number: 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 a port number of more than 1024.
Protocol: in computer network, the rules of connection and communication are called network communication protocol
UDP protocol: user datagram protocol, which is a connectionless communication protocol. Because UDP protocol consumes less resources and has high communication efficiency, it is usually used for the transmission of audio, video and ordinary data. However, UDP protocol is not recommended when transmitting important data
TCP protocol: transmission control protocol is a connection oriented communication protocol, that is, before transmitting data, establish a logical connection between the sending end and the receiving end, and then transmit data. It provides reliable and error free data transmission between two computers. In TCP connection, the client and server must be specified. The client sends a connection request to the server. Each connection creation needs to go through "three handshakes"
Three handshakes: in TCP protocol, three interactions between the client and the server in the preparation stage of sending data to ensure the reliability of the connection
For the first handshake, the client sends a connection request to the server and waits for the server to confirm
In the second handshake, the server sends back a response to the client to notify the client that it has received the connection request
For the third handshake, the client sends confirmation information to the server again to confirm the connection
After three handshakes are completed and the connection is established, the client and server can start data transmission. This connection oriented protocol can ensure the security of data transmission.

2, UDP communicator

2.1 UDP communication principle

UDP protocol is an unreliable network protocol. It establishes a Socket object at both ends of the communication, but these two sockets are only the objects to send and receive data. Therefore, for both sides of communication based on UDP protocol, there is no so-called concept of client and server
JAVA provides the DaragramSocket class as a Socket based on UDP protocol
To send data:
1. Create a Socket object (DatagranmSocket) at the sending end
2. Create data and package it with dategram packet (byte [] buf, int length, InetAddress, address, int port)
3. Call the method of datagram socket object to send data: void send (datagram socket P);
4. Close the sender: void close();
Steps for receiving data:
1. Create the Socket object (DaragramSocket) of the receiving end: DatagramSocket(int port)
2. Create a data packet to receive data: datagram packet (byte [] buf, int length)
3. Call the method of datagram socket object to receive data: void receive (datagram packet P)
4. Parse the data package and display the data on the console: byte[] getData(); int getLength();
5. Close the receiver

2.2 UDP communication program practice

UDP sending data: the data comes from the keyboard input until the input data is 886, and the sending data ends
UDP receiving data: because the receiving end does not know when the sending end will stop sending, it adopts dead loop receiving

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("Input:");
		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("The data are:"+new String(dp.getData(),0,dp.getLength()));
			
			
		}
		
	}
}

3, TCP communication program

3.1 TCP communication principle

TCP communication protocol is a reliable network protocol. It establishes a Socket object at both ends of the communication, so as to form a network virtual link at both ends of the communication. Once the virtual network link is established, the programs at both ends can communicate through the virtual link.
java provides a good package for the network based on TCP protocol, uses Socket object to represent the communication ports at both ends, and generates IO flow through Socket for network communication
Java provides a Socket class for the client and a ServerSocket class for the server
To send data:
1. Create the Socket object (Socket) of the client: Socket(String host,int port)
2. Get output stream and write data: OutputStream getOutputStream()
3. Release resources: void close();
Steps for receiving data:
1. Create a server-side Socket object (ServerSocket): ServerSocket (int port)
2. Listen to 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 {
		
		//Create the Socket object of the client
		Socket s = new Socket("192.168.2.225",10000);
		
		//Get output stream and write data
		OutputStream os = s.getOutputStream();
		os.write("hello,I'm coming.".getBytes());
		
		//Receive server feedback
		InputStream is = s.getInputStream();
		byte[] bys = new byte[1024];
		int len = is.read(bys);
		String data = new String(bys,0,len);
		System.out.println("client:"+data);
		
		//Release resources
		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 {
		
		//Create a Socket object on the server side
		ServerSocket ss = new ServerSocket(10000);
		
		//Listen to the client connection and return a Socket object
		Socket s = ss.accept();
		
		//Get the input stream, read the data, and display the data on the console
		InputStream is = s.getInputStream();
		byte[] bys = new byte[1024];
		int len = is.read(bys);
		String data = new String(bys,0,len);
		System.out.println("The server:"+data);
		
		//Give feedback
		OutputStream os = s.getOutputStream();
		os.write("Data received".getBytes());
		
		//Release resources
		ss.close();
	}
}

Topics: Java network