Javaa Learning Note Day12: Network Programming

Posted by zuessh on Thu, 03 Mar 2022 19:58:28 +0100

1. Network programming (simple code, but deep complexity)

Overview of 1.1 Network Programming

1.1.1 Classification

Network programming: BIO,NIO,AIO

BIO (base): Blocking communication (data flow is limited, waiting for the last batch to be released)

(1) In the process of communication, there must be one sender and one receiver.

(2) Before sending data, first make sure the address of the target server (IP/domain name)

(3) For the convenience of remembering network addresses, domain names arise and are resolved by DNS servers; A server that provides a huge MAP, KEY is the domain name, and VALUE is the IP.

note: free servers on the web

(4) The first access is to the local hosts file, if not, it will go to DNS resolution

Path: C:\Windows\System32\driversetchosts

For example: append a line 14.215.111.38 baidu to the last line in hosts

Then in cmd command line mode, ping baidu works just like ping www.baidu.com is the same

(5) Port: Address (IP) + Recipient (Port); Each computer connected to the network has a total of 65536 ports, 256*256, ranging from 0 to 65535, divided into recognized ports (0-1023) such as 80 ports which are virtually always HTTP communication, registered ports (1024 to 49151), dynamic and/or private ports (49152 to 65535).

NIO: Non-blocking

AIO:

1.1.2 What are the benefits of networking? What can you do with the Internet?

(1) Interconnected computers

(2) Shared resources

(3) Exchange of data: e.g. streaming media

1.1.3 What is an IP address? Why do I need an IP address?

Analogue post office delivery, need address; Communication between two computers, both must have addresses

Composition of IP address:

(1) IP address: uniquely identifies each computer on the network

(2) IP address composition: 32 bits, composed of 4 8-bit binary numbers, inconvenient to become 10-bit

(3) IP address = network address (identifying the segment where the computer or network device is located) + host address (identifying a specific host or network device)

1.1.4 Network Communication Protocol

Network communication protocol: A collection of rules, standards, or conventions established to communicate between different computers in a network

Four-layer protocol is the most widely used protocol at present.

There are two protocols

(1) Standards already agreed upon and applicable in most cases

(2) Some agreements designed by companies or departments or organizations according to their own needs;

1.1.5 Data Encapsulation and Disassembly

The purpose of protocol design is to transfer data, data needs to be encapsulated and unpacked during transmission, especially because the network environment is more and more complex today, we also need to encrypt and decrypt data when necessary.

1.2InetAddress class

Introduction to 1.2.1 Socket

1.2.1.1 What is a Socket?
  • The endpoint of a communication link is called a Socket.
  • Is the interface that provides the application
  • The underlying mechanisms of Sockets are complex, and the Java platform provides some simple API s to make it easier and more efficient to develop with Sockets without knowing the underlying mechanisms.
  • Analogue: Express point in the process of logistics delivery.
1.2.1.2 Implementing Socket

1. Make sure the server (girlfriend) is remote and you need to turn off the firewall (whitelist)

(2) Clear client (male friend)

(3) Between the server and the client, usually the client initiates the request to the server actively first;

(4) To establish normal communication, the IP and port of the client must be the same as that of the server. In fact, three handshakes have been completed in this step.

Any application can be either a server or a client, a two-way channel (instant push), the oldest distributed with socket s, without dubbo or springCloud, web services are polling, and push and polling are two means in the network, each with its own benefits.

Communication is done through data streams, do not use buffered streams because they have buffers themselves

Once the stream is closed, the socket link will also be closed

Byte streams are slightly cumbersome without using them

  1. Binary stream: no need to prepare serialized objects beforehand

  2. Serialization and Deserialization: Serialized objects are required. The advantage is that you can put data directly into objects. The disadvantage is that you need to create the same serialized objects in different projects

_Single-threaded, continuous communication

  1. Cycles are used both on the server and on the client to ensure continuity of communication

  2. Think: Not multi-client, not multi-threaded
    a. Two-way channel
    b. Registry

1.2.1.3 Code Sample

1.2.1.3.1 byte stream (byte streams are a bit cumbersome without using them):

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientTest {

	public static void main(String[] args) throws Exception {
		
		//Client
		Socket socket = new Socket(InetAddress.getByName("localhost").getHostAddress(), 9999);
		//Send out information
		OutputStream out = socket.getOutputStream();
		out.write("Hello Server".getBytes());
		out.flush();
		
        //Once the stream is closed, the socket link will also be closed, so do not close the stream halfway
        //in.close(); 
        
		//Receive server response
		InputStream in = socket.getInputStream();
		byte[] buf = new byte[in.available()];
		in.read(buf);
		String requestStr = new String(buf);
		System.out.println("Client Receive:"+requestStr);
		
		out.close();
		in.close();
	}

}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerTest {

	public static void main(String[] args) throws Exception {
		
		//The server
		ServerSocket server = new ServerSocket(9999);
		//Get listening: Listen for client-side requests for access
		Socket socket = server.accept();
		System.out.println("Get access to socket");
		
		//1. Receiver
		InputStream in = socket.getInputStream();
		byte[] buf = new byte[in.available()];
		in.read(buf);
		String requestStr = new String(buf);
		System.out.println("Server Receive:"+requestStr);
		
		//2. Response
		OutputStream out = socket.getOutputStream();
		out.write("Hello Client".getBytes());
		out.flush();
		
		in.close();
		out.close();
		socket.close();
	}

}

1.2.1.3.2 binary stream (recommended):

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientTest {

​	public static void main(String[] args){
​		
​		//Client
​		Socket socket = null;
​		try {
​			//Send out
​			socket = new Socket(InetAddress.getByName("localhost").getHostAddress(), 9999);
​			DataOutputStream out = new DataOutputStream(socket.getOutputStream());
​			out.writeUTF("Hello Server");
​			//Receive
​			DataInputStream in = new DataInputStream(socket.getInputStream());
​			String msg = in.readUTF();
​			System.out.println("Client Receive:"+msg);
​		} catch (UnknownHostException e) {
​			// TODO Auto-generated catch block
​			e.printStackTrace();
​		} catch (IOException e) {
​			// TODO Auto-generated catch block
​			e.printStackTrace();
​		}
​	}

}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerTest {

​	public static void main(String[] args) throws Exception {
​		
​		//The server
​		ServerSocket server = new ServerSocket(9999);
​		//Get listening: Listen for client-side requests for access
​		Socket socket = null;
​		try {
​			socket = server.accept();
​			//Receive
​			DataInputStream in = new DataInputStream(socket.getInputStream());
​			String msg = in.readUTF();
​			System.out.println("Server Receive:"+msg);
​			//Send out
​			DataOutputStream out = new DataOutputStream(socket.getOutputStream());
​			out.writeUTF("Hello Client");
​		} catch (UnknownHostException e) {
​			// TODO Auto-generated catch block
​			e.printStackTrace();
​		} catch (IOException e) {
​			// TODO Auto-generated catch block
​			e.printStackTrace();
​		} finally{
​			if(socket != null){
​				socket.close();
​			}
​		}
​	}

}

1.2.1.3.3 Serialization and Deserialization (the downside is that you need to create the same serialization object in different projects): Apache Dubb Ali is obsolete and consuming performance

package com.m.demo04;//Project for demo04
import java.io.Serializable;

public class Message implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3585042586346181359L;
	

	private String msg;
	
	public String getMsg() {
		return msg;
	}
	
	public void setMsg(String msg) {
		this.msg = msg;
	}

}
package com.m.demo04;//Project for demo04
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import com.m.entity.Message;

public class ServerTest {

	public static void main(String[] args) throws Exception {
		
		//The server
		ServerSocket server = new ServerSocket(9999);
		//Get listening: Listen for client-side requests for access
		Socket socket = null;
		try {
			socket = server.accept();
			//Receive
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
			Object obj = in.readObject();
			if(obj instanceof Message){
				Message msg = (Message)obj;
				System.out.println("Server Receive:"+msg.getMsg());
			}
			
			//response
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			Message msg = new Message();
			msg.setMsg("Hello Client");
			out.writeObject(msg);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(socket != null){
				socket.close();
			}
		}
	}

}
package com.m.entity;//Different projects from demo

import java.io.Serializable;

public class Message implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3585042586346181359L;
	

	private String msg;
	
	public String getMsg() {
		return msg;
	}
	
	public void setMsg(String msg) {
		this.msg = msg;
	}

}
package com.m.demo;and demo Different Projects

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import com.m.entity.Message;

public class ClientTest {

	public static void main(String[] args){
		
		//Client
		Socket socket = null;
		try {
			//Send out
			socket = new Socket(InetAddress.getByName("localhost").getHostAddress(), 9999);
			//response
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			Message msg = new Message();
			msg.setMsg("Hello Server");
			out.writeObject(msg);
			
			//Receive
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
			Object obj = in.readObject();
			if(obj instanceof Message){
				msg = (Message)obj;
				System.out.println("Client Receive:"+msg.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(socket != null){
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

1.2.1.3.4 Single-threaded continuous communication:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientTest {

	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		while(true){
			//Client
			Socket socket = null;
			try {
				//Send out
				socket = new Socket(InetAddress.getByName("localhost").getHostAddress(), 9999);
				DataOutputStream out = new DataOutputStream(socket.getOutputStream());
				System.out.print("Please enter:");
				out.writeUTF(scanner.nextLine());
				//Receive
				DataInputStream in = new DataInputStream(socket.getInputStream());
				String msg = in.readUTF();
				System.out.println("Client Receive:"+msg);
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally{
				if(socket != null){
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ServerTest {

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		//The server
		ServerSocket server = new ServerSocket(9999);
		//Get listening: Listen for client-side requests for access
		while(true){
			Socket socket = null;
			try {
				socket = server.accept();//New listens are acquired after each loop ends
				//Receive
				DataInputStream in = new DataInputStream(socket.getInputStream());
				String msg = in.readUTF();
				System.out.println("Server Receive:"+msg);
				//Send out
				DataOutputStream out = new DataOutputStream(socket.getOutputStream());
				System.out.print("Please enter:");
				out.writeUTF(scanner.nextLine());
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally{
				if(socket != null){
					socket.close();
				}
			}
		}
	}

}

1.2.2java.net package

  • Socket
  • ServerSocket
  • DatagramPacket
  • DatagramSocket
  • InetAddress

1.2.3InetAddress example

InetAddress: An object of a network address that provides basic information about the network on which the current host is located

import java.net.InetAddress;
import java.net.UnknownHostException;
//The first element of network communication: IP address, unique location, unique location of a host through IP address
//InnetAddress is located in java.net under this package
//1.InetAddress is used to represent an IP address. An InetAddress object represents an IP address
//2. How to create an object for InetAddress, InetAddress.getByName("");
//3.getHostName() is used to get the domain name corresponding to the IP address
//  getHostAddress() is used to get an IP address

public class Test {
	public static void main(String[] args) throws Exception {
		//An object for a network address
		InetAddress ia = InetAddress.getByName("localhost");//121.0.0.1, equivalent to local IP access
		System.out.println(ia.getHostName());
		System.out.println(ia.getHostAddress());//121.0.0.1
		System.out.println(ia.getLocalHost());//The physical name/host IP address of the computer
	}

}

1.3TCP/IP

1.3.1 Three-Way Handshake

(1) The requester asks the server: Are you there? I want to talk to you!

(2) The server receives a request for reply: I know, you want to chat, you can.

Ask for final confirmation: I know you know I want to chat with you, so let's start chatting

(4) Formal connection established after three handshakes

  1. The purpose is to ensure the absolute security, orderly, effective and complete transmission of data to the other party.

  2. Benefits: Absolute data security

1.3.2 Socket Programming Based on TCP Protocol

Socket programming based on TCP protocol: for two-way secure connection network communication

Socket communication model: When network communication is conducted, Socket needs to use data streams to complete the data transfer work

1.3.3Socket network programming can generally be divided into the following steps

1.3.3 Simulate user login

Implements the client to send login user information, the server side displays the login letter and responds to the client's successful login

Implement object transfer in 1.3.4 Socket

How does 1.3.4.1 transfer object information?

serialize

ObjectOutputStream  oos = new  ObjectOutputStream(...);
oos.writeObject(...);

ObjectInputStream  ois = new  ObjectInputStream(...);
Object = ois.readObject();
How can 1.3.4.2 fulfill multi-client requests?
  • Multi-threaded
  • An Application Master Service program dedicated to monitoring
  • A threading program dedicated to processing requests
1.3.4.3 Single server provides network services to multiple clients

In practical programming, we usually need a server to provide network services to multiple clients. To enable a server to provide network services to multiple clients, start a separate thread to service the current client after accepting the request.

1.3.4.4 Multi-client user login

Requirement Description
Upgrade previous hosting content for multi-client user login
Analysis
Create a server-side thread class and implement response processing to a request in the run() method
Modify server-side code to achieve circular listening state
Server creates a processing thread for each request it hears

1.4UDP

1.4.1 Socket programming based on UDP protocol

Step 1.4.1.1

1.4.1.2 Sender:
//Create DatagramSocket object, bind port 3456
DatagramSocket sendSocket = new DatagramSocket(3456);
//Prepare the data to be sent, type byte[]
String string = "Hello,I come form ICSS!";
byte[] databyte = new byte[100];
databyte = string.getBytes();
//Create a datagram encapsulating the data to be sent, the length of the data, the server address, and the server port of 5000
DatagramPacket sendPacket = new DatagramPacket(databyte,
string.length(), InetAddress.getByName("121.0.0.1"), 5000);
//Send datagram sendPacket to server using DatagramSocket object
sendSocket.send(sendPacket);
System.out.println("send data:" + string);
1.4.1.2 Receiver
//Create a DatagramSocket object to receive data on port 5000
DatagramSocket receiveSocket = new DatagramSocket(5000);
byte buf[] = new byte[1000];
DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
System.out.println("startinig to receive packet");
while (true) {
//Receiving datagrams using DatagramSocket
receiveSocket.receive(receivePacket);
//Parse the information in the datagram to get the host name and port, data, etc.
String name = receivePacket.getAddress().toString();
System.out.println("From host:" + name + "Port:"+ receivePacket.getPort());
String s = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("receive data: " + s);
}

User Status Tracking for 1.4.2 UDP Protocol Communication

  • Unlike sockets, UDP is a typical stateless protocol (that is, two nodes of UDP communication cannot get the online status of each other), so it is less convenient in the real-time communication field to determine whether the client is offline than Socket (one end drops off while the other side throws an exception).
  • In this case, the server needs to complete periodic inquiries in order to get the client's online information. If the result of inquiries can get automatic feedback from the client within the specified time, the client is still online, otherwise the client is offline (i.e., heartbeat information).

1.4.3TCP and UDP

** **TCPUDP
Connect or notConnection-orientedNon-Connection Oriented
Transmission reliabilityreliableUnreliable
speedslowfast

1.5 Summary

  • Computers in the network have unique IP addresses so that different hosts can distinguish one another.
  • Client-server is one of the most common network application models. A server is hardware or software that provides a particular service to its clients. A client is a user application that accesses services provided by a server. A port number is a place of access to a service and is used to distinguish multiple services on the same physical computer. Sockets are used to connect clients and servers, and each communication session between the client and server uses a different socket. The TCP protocol is used to implement connection-oriented sessions.
  • Java has network-related functions defined in java.net package. Java uses the InetAddress object to represent IP addresses, which has two fields: a host name (String) and an IP address (int).
  • Class Sockets and ServerSocket s implement client-server programs based on TCP protocol. A Socket is a connection between a client and a server, and the details of connection creation are hidden. This connection provides a secure data transmission channel because the TCP protocol solves the problems of data loss, corruption, duplication, disorder and network congestion during transmission. It ensures reliable data transmission.

Topics: Java