Chapter 11 network programming

11.1 introduction to network programming

11.1.1 overview of network programming

Computer network: refers to a computer system that connects multiple computers with independent functions and their external equipment in different geographical locations through communication lines and realizes resource sharing and information transmission under the management and coordination of network operating system, network management software and network communication protocol

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

11.1.2 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. Through this identification number, the computer to receive data and the computer to identify the sending computer must be specified, and the IP address is this identification number. That is, the identification of the equipment
  • 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
  • agreement

    • 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 cars driving on the road must abide by traffic rules. In the computer network, these connection and communication rules are called network communication protocol. It makes unified provisions on the data transmission format, transmission rate and transmission steps. Both sides of the communication must abide by them at the same time to complete the data exchange. The common protocols are UDP and TCP

11.1.3 IP address

IP address: it is the unique identification of the device in the network

IP addresses fall into two categories

  • IPv4: assign a 32bit address to each host connected to the network. Press

    • According to TCP/IP regulations, IP addresses are expressed in binary. Each IP address is 32bit long, that is, 4 bytes. For example, an IP address in binary form is "11000000 10101000 00000001 01000010". It's too hard to handle such a long address.
    • For ease of use, IP addresses are often written in decimal form with the symbol "." Separate different bytes. Therefore, the above IP address can be expressed as "192.168.1.66". This representation of IP address is called dotted decimal representation, which is obviously much easier to remember than 1 and 0
  • IPv6: due to the vigorous development of the Internet, the demand for IP address is increasing, but the limited network address resources make the allocation of IP more and more tense. In order to expand the address space, the address space is redefined through IPv6, and the 128 bit address length is adopted. Each 16 bytes is divided into 8 groups of hexadecimal numbers, which solves the problem of insufficient network address resources

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

11.1.4 use of InetAddress

InetAddress: this class represents an Internet Protocol (IP) address

Method nameexplain
static InetAddress getByName(String host)Determine the IP address of the host name. The host name can be either a machine name or an IP address
String getHostName()Gets the host name of this IP address
String getHostAddress()Returns the IP address string in the text display
package javasea.Net;

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

public class InetAddressDemo {
	public static void main(String[] args) throws UnknownHostException {
//		 static  InetAddress getByName(String host)  
		InetAddress address=InetAddress.getByName("LAPTOP-6JTT8IE2");
		
//		String  getHostName()  
		String name=address.getHostAddress();
		
//		 String  getHostAddress() 
		String ip=address.getHostAddress();
		
		System.out.println(name);
		System.out.println(ip);
	}
}

11.1.5 port

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 and 1023 is used for some well-known network services and applications

Ordinary applications need to use port numbers above 1024

If the port number is occupied by another service or application, the current program will fail to start

11.1.6 agreement

Protocol: in computer network, the rules of connection and communication are called network communication protocol

UDP protocol

  • User datagram protocol

  • UDP is a connectionless communication protocol, that is, during data transmission, the sender and receiver of data do not establish a logical connection. In short, when a computer sends data to another computer, the sender will send data without confirming whether the receiver exists. Similarly, when the receiver receives data, it will not feed back whether it has received data to the sender.

  • Because UDP protocol consumes less resources and has high communication efficiency, it is usually used for the transmission of audio, video and ordinary data

  • For example, video conference usually adopts UDP protocol, because even if one or two packets are lost occasionally, it will not have a great impact on the receiving results. However, when using UDP protocol to transmit data, due to the non connectivity of UDP, the integrity of data cannot be guaranteed. Therefore, it is not recommended to use UDP protocol when transmitting important data

TCP protocol

  • Transmission control protocol

  • TCP 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

    • ·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 a confirmation message 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. Because of this connection oriented feature, TCP protocol can ensure the security of data transmission, so it is widely used. Such as uploading files, downloading files, browsing web pages, etc

11.2 udp communication program

11.2.1 udp communication principle

UDP protocol is an unreliable network protocol. It establishes a Socket object at both ends of the communication, but the two sockets are only objects for sending and receiving data

Therefore, for both sides of communication based on UDP protocol, there is no so-called concept of client and server

Java provides DatagramSocket class as a Socket based on UDP protocol

11.2.2 udp sending data

① Create a Socket object (DatagramSocket) at the sending end

Datagram socket() constructs a datagram socket and binds it to any available port on the local host

② Create data and package it

Datagram packet (byte [] buf, int length, InetAddress, address, int port) constructs a data packet and sends the data packet with length to the specified port number on the specified host

③ Call the method of DatagramSocket object to send data

Void send (datagram packet P) sends datagrams from this socket

④ Close sender

void close() closes the datagram socket

package javasea.Net;

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

public class SendDemo {
	public static void main(String[] args) throws IOException {
//		① Create a Socket object (DatagramSocket) at the sending end
//		DatagramSocket()
		DatagramSocket dSocket=new DatagramSocket();

//		② Create data and package it
//		DatagramPacket(byte[] buf, int length, InetAddress address, int port)
		byte[] b="hello udp".getBytes();
		int length=b.length;
		InetAddress address=InetAddress.getByName("192.168.10.133");
		int port=10086;
		DatagramPacket dp=new DatagramPacket(b, length,address,port);
		
//		③ Call the method of DatagramSocket object to send data
//		void send(DatagramPacket p)
		dSocket.send(dp);

//		④ Close sender
//		void close()
		dSocket.close();
	}
}

11.2.3 receiving data

① Create a Socket object (datagram Socket) at the receiving end

Datagram socket (int port) constructs a datagram socket and binds it to any available port on the local host

② Create a packet to receive data

Datagram packet (byte [] buf, int length) constructs a datagram packet to accept data packets with length

③ Call the method of DatagramSocket object to receive data

void receive(DatagramPacket p)

④ Parse the data package and display the data on the console

byte[] getData() return data buffer

int getLength() returns the length of data to be sent or received

⑤ Close the receiver

void close()

package javasea.Net;

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

public class ReceiveDemo {
	public static void main(String[] args) throws IOException {
//		Create a Socket object (datagram Socket) at the receiving end
//		DatagramSocket​(int port)
		DatagramSocket dSocket=new DatagramSocket(10086);
		
//		Create a packet to receive data
//		DatagramPacket​(byte[] buf, int length)
		byte[] bys=new byte[1024];
		DatagramPacket dp=new DatagramPacket(bys,bys.length);
				
//		Call the method of DatagramSocket object to receive data
//		void receive​(DatagramPacket p)
		dSocket.receive(dp);
		
//		Parse the data package and display the data on the console
//		byte[] getData​()
//		int getLength​()
		byte[] datas=dp.getData();
		int len=dp.getLength();
		String dataString=new String(datas,0,len);
		System.out.println("Data is"+dataString);
		
//		Close the receiver
//		void close()
		dSocket.close();

	}
}

11.2.4 implement the program according to the following requirements

UDP sending data: the data comes from 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 stops sending, it adopts dead loop receiving

SendDemo

package javasea.Net;

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.util.zip.InflaterInputStream;

public class SendDemo {
	public static void main(String[] args) throws IOException {
//		Create a Socket object (datagram Socket) at the sending end
		DatagramSocket dSocket = new DatagramSocket();

//		Encapsulate the keyboard to enter data
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while ((line = bufferedReader.readLine()) != null) {
//			The input data is 886, and the sending data ends
			if ("886".equals(line)) {
				break;
			}
//			Create data and package it
			byte[] b = line.getBytes();
			DatagramPacket dp = new DatagramPacket(b, b.length);

//			③ Call the method of DatagramSocket object to send data
			dSocket.send(dp);
		}

//		④ Close sender
		dSocket.close();
	}
}

ReceiveDemo

package javasea.Net;

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

public class ReceiveDemo {
	public static void main(String[] args) throws IOException {
//		Create a Socket object (datagram Socket) at the receiving end
		DatagramSocket dSocket=new DatagramSocket(12345);
		
//		Create a packet to receive data
		byte[] bys=new byte[1024];
		DatagramPacket dp=new DatagramPacket(bys,bys.length);
				
//		Call the method of DatagramSocket object to receive data
		dSocket.receive(dp);
		
//		Parse the data package and display the data on the console
		byte[] datas=dp.getData();
		int len=dp.getLength();
		String dataString=new String(datas,0,len);
		System.out.println("Data is"+dataString);
		
//		Close the receiver
		dSocket.close();

	}
}

11.3 tcp communication program

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

11.3.2 TCP sending data

① Create the client's Socket object (Socket)

Socket(String host, int port) creates a stream socket and connects it to the specified window number of the specified ip address

② Get output stream and write data

OutputStream getOutputStream() returns the output stream of this socket

③ Release resources

void close()

package javasea.Net;

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

public class ClientDemo {
	public static void main(String[] args) throws UnknownHostException, IOException {
//		Create the client's Socket object (Socket)
//		Socket​(String host, int port)
		Socket socket=new Socket("192.165.10.131",10000);
		
//		Get output stream and write data
//		OutputStream getOutputStream​()
		OutputStream outputStream=socket.getOutputStream();
		outputStream.write("aaaaa".getBytes());
		
//		Release resources
//		void close​()
		socket.close();

	}
}

11.3.3 TCP receiving data

① Create a server-side Socket object (ServerSocket)

ServerSocket(int port) creates a server socket bound to a specified port

② Listen to the client connection and return a Socket object

Socket accept() listens to the socket you want to connect to and accepts it

③ Get the input stream, read the data, and display the data on the console

==InputStream getInputStream() ==

④ Release resources

void close()

package javasea.Net;

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

public class ServerDemo {
	public static void main(String[] args) throws IOException {
//		Create a server-side Socket object (ServerSocket)
//		ServerSocket​(int port)
		ServerSocket serverSocket=new ServerSocket(10000);
//		Listen to the client connection and return a Socket object
//		Socket accept​()
		Socket socket=serverSocket.accept();
//		Get the input stream, read the data, and display the data on the console
//		InputStream getInputStream​() 
		InputStream inputStream=socket.getInputStream();
		byte[] bys=new byte[1024];
		int len=inputStream.read(bys);
		String dataString=new String(bys,0,len);
		System.out.println("Data is"+dataString);
//		Release resources
//		void close​()
		socket.close();
		serverSocket.close();

	}
}

Added by Dark-Elk on Fri, 21 Jan 2022 02:27:24 +0200