Want to know how Java Web communication develops. Is TCP and IP protocol just TCP and IP protocol?

Author: Le byte - Keng Wang Lao Xue

For our developers who study technology, there are many technologies. At present, they may feel very complex and powerful, but in fact, all these technologies have been achieved through the gradual efforts of predecessors from the most basic functions over time. We are standing on the shoulders of many giants. Today, let's see how the server has developed slowly.

Mode of communication

  • Simple communication
  • Different requests
  • Complex request

Case practice

Simple communication

review Socket Programming gives us the greatest feeling that we can transmit data between multiple computers, which is the beginning and foundation of network programming. We can more intuitively understand the development process of the Web by understanding the communication between the client and the server.

Client

/**
 * Client: Send a request to the server and send a simple message
 * @author Pit King Lao Xue
 *
 */
public class Client {
	
	public static void main(String[] args) throws UnknownHostException, IOException {
		// Server + port must be specified when creating a client
		Socket client = new Socket("localhost", 8888);
		// Send message request resource
		// Get output stream
		OutputStream os = client.getOutputStream();
		// Output stream using buffered characters
		BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os));
		// Write messages and send content
		String msg = "Hello, I am Client, I need some resources";
		br.write(msg);
		br.close();
	}
	
}

Server

/**
 * The server receives the client request and gives a simple response
 * @author Pit King Lao Xue
 *
 */
public class Server {
	
	public static void main(String[] args) throws IOException{
		// Create a server and specify the port ServerSocket(int port)
		ServerSocket socket = new ServerSocket(8888);
		// Receive client connections
		Socket client = socket.accept();
		System.out.println("******************");
		// Get the input stream of data
		InputStream is = client.getInputStream();
		// Use buffered character input stream
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String msg = "";
		while ((msg = br.readLine()) != null) {
			System.out.println(msg);
		}
		br.close();
	}
	
}

Server console:

From the above example, the communication conditions are summarized as follows:

  1. Need to have a server: waiting to be requested, you need to expose the ip and port
  2. A client is required: initiate a request and know the ip and port of the server
  3. Communication rules (Protocol): TCP/IP agreement

ip is used to locate the computer; Port number (locator), which is used to identify the logical address of the process and the marks of different processes; Effective ports: 0 ~ 65535, of which 0 ~ 1023 are used or reserved by the system. It is recommended to use ports above 1024 in development.

Different requests

Client

/**
 * Client: send requests to the server and send different requests
 * @author Pit King Lao Xue
 *
 */
public class Client {
	
	public static void main(String[] args) throws IOException {
		// Create an unconnected socket through the system default type of SocketImpl
		Socket socket = new Socket();
		// This class implements IP socket address (IP address + port number). It can also be a pair (hostname + port number), in which case an attempt will be made to resolve the hostname
		SocketAddress address = new InetSocketAddress("localhost", 8898);
		// Connect this socket to the server and specify a timeout value. Or do not specify a timeout
		socket.connect(address, 1000);
		OutputStream os = socket.getOutputStream();
		os.write("time".getBytes());
		os.flush();
		socket.close();
	}
	
}

Server

/**
 * Server 
 * public class ServerSocketextends Object: This class implements server sockets.
 * The server socket waits for a request to pass through the network.
 * It performs certain operations based on the request and may then return results to the requester.
 * 
 * @author Pit King Lao Xue
 *
 */
public class Server {
	public static void main(String[] args) throws IOException {
		// Create a server socket bound to a specific port.
		ServerSocket server = new ServerSocket(8898);

		// Socket accept() listens and accepts connections to this socket.
		Socket client = server.accept();
		System.out.println("Connection received");

		InputStream is = client.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] req = new byte[1024];
		// Receive client requests
		int len = bis.read(req);
		String reqStr = new String(req, 0, len);
		System.out.println(reqStr);
		if (reqStr.equals("money")) {
			System.out.println("here's the money");
		} else if (reqStr.equals("time")) {
			System.out.println("you have so much time");
		}
		client.close();
		server.close();
	}
}

Server console:

Complex request

Client

/**
 * client
 * 
 * @author Pit King Lao Xue
 *
 */
public class Client {
	
	public static void main(String[] args) throws IOException {
		// Create an unconnected socket through the system default type of SocketImpl
		Socket socket = new Socket();
		// This class implements IP socket address (IP address + port number). It can also be a pair (hostname + port number), in which case an attempt will be made to resolve the hostname
		SocketAddress address = new InetSocketAddress("localhost", 8898);
		// Connect this socket to the server and specify a timeout value. Or do not specify a timeout
		socket.connect(address, 1000);

		OutputStream os = socket.getOutputStream();
		os.write("money".getBytes());
		os.flush();
		// Receive the response and display the result
		InputStream is = socket.getInputStream();
		byte[] result = new byte[1024];
		int len = is.read(result);
		String resultStr = new String(result, 0, len);
		System.out.println(resultStr);
		socket.close();
	}
	
}

Server

/**
 * Server
 * @author Pit King Lao Xue
 *
 */
public class Server2 {
	
	public static void main(String[] args) throws IOException {
		// Create a server socket bound to a specific port.
		ServerSocket server = new ServerSocket(8898);

		// Socket accept() listens and accepts connections to this socket.
		Socket client = server.accept();
		System.out.println("Connection received");
		InputStream is = client.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] req = new byte[1024];
		// Receive client requests
		int len = bis.read(req);
		String reqStr = new String(req, 0, len);
		System.out.println(reqStr);
		// Encapsulate the received request into an object and send it to the requested class
		MyRequest request = new MyRequest();
		MyResponse response = new MyResponse();

		OutputStream os = client.getOutputStream();
		if (reqStr.equals("money")) {
			// Construct the processing class according to the requested information
			MyServlet s1 = new ServletMoney();
			s1.service(request, response);
			// Respond the result back to the client through the response of the client
			os.write("here's the money".getBytes());
			os.flush();
		} else if (reqStr.equals("time")) {
			// Construct the processing class according to the requested information
			MyServlet s2 = new ServletTime();
			s2.service(request, response);
			// Respond the result back to the client through the response of the client
			os.write("you have somuch time".getBytes());
			os.flush();
		}
		client.close();
		server.close();
	}
	
}

/*
 * I am a person with requirements. The resource you request must be a class that meets the format I require. Its function is to prevent confusion and facilitate calling. This is my standard
 */
interface MyServlet {
	void service(MyRequest req, MyResponse resp);
}

class ServletMoney implements MyServlet {
	/*
	 * @see com.mage.server.MyServlet#service(com.mage.server.MyRequest, com.mage.server.MyResponse)
	 */
	@Override
	public void service(MyRequest req, MyResponse resp) {
		// Handle as much as the output can
	}
}

class ServletTime implements MyServlet {
	/*
	 * @see com.mage.server.MyServlet#service(com.mage.server.MyRequest, com.mage.server.MyResponse)
	 */
	@Override
	public void service(MyRequest req, MyResponse resp) {
		// Handle as much as the output can
	}
}

/*
 * The request information is encapsulated in the object according to the law
 */
class MyRequest {
}

class MyResponse {
}

Server console: Client console:

With the increasingly complex needs of customers and more functions, our server needs to process more and more requests. We need to distinguish different requests, extract request data, allocate and calculate resources according to different requests, and deal with them logically. Finally, we need to respond to the client, which makes the server code more and more complex and difficult to implement.

According to the past experience, the two sides can clearly know the meaning of each part of the data only by following certain rules. Therefore, an application protocol (HTTP protocol) on the upper layer of the network appears, which stipulates the communication rules between the server and the client.

The client requests the server and the server responds to the client according to fixed rules, so the operation of receiving request and response data can be fixed and handed over to a specific piece of code to execute, so as to reduce the amount of code on the server, so it slowly evolved into the server we use now.

Extended ~ TCP/IP protocol cluster

concept

TCP/IP protocol cluster (Transmission Control Protocol/Internet Protocol) refers to the protocol cluster that can realize information transmission between multiple different networks.

TCP/IP protocol refers not only to the two protocols of TCP and IP, but also to a protocol cluster composed of FTP, SMTP, TCP, UDP, IP and other protocols. Just because TCP protocol and IP protocol are the most representative in TCP/IP protocol, it is called TCP/IP protocol.

TCP/IP transmission protocol is strictly a four layer architecture, including application layer, transmission layer, network layer and data link layer.

application layer

The application layer directly provides services for the application process. For different kinds of applications, different protocols of the application layer will be used according to their own needs. For example, the mail transmission application uses SMTP protocol, the world wide web application uses HTTP protocol, the file transmission application uses FTP protocol, the remote login service application uses TELNET protocol, and so on.

Transport layer

The transmission layer provides data transmission between two computers in the network connection to the upper application layer.

There are two different protocols in the transport layer:

  • TCP (transmission control protocol)
  • UDP (User Data Protocol).

network layer

The network layer is used to process data packets flowing on the network. Data packet is the smallest data unit transmitted by the network. This layer specifies the path (so-called transmission route) to reach the other party's computer and transmit the data packet to the other party. The network layer can establish and terminate the network connection and find the IP address.

link layer

The link layer is used to handle the hardware part of the connected network. It includes the device driver controlling the operating system and hardware, NIC (Network Interface Card), optical fiber and other physical visible parts (including connectors and other transmission media). The scope of hardware is within the scope of the link layer.

Transmission diagram

According to the above concepts and the introduction of the four layers of TCP/IP, we can see how the TCP/IP protocol transmits data step by step in network transmission.

network layer

The network layer is used to process data packets flowing on the network. Data packet is the smallest data unit transmitted by the network. This layer specifies the path (so-called transmission route) to reach the other party's computer and transmit the data packet to the other party. The network layer can establish and terminate the network connection and find the IP address.

link layer

The link layer is used to handle the hardware part of the connected network. It includes the device driver controlling the operating system and hardware, NIC (Network Interface Card), optical fiber and other physical visible parts (including connectors and other transmission media). The scope of hardware is within the scope of the link layer.

Transmission diagram

According to the above concepts and the introduction of the four layers of TCP/IP, we can see how the TCP/IP protocol transmits data step by step in network transmission.

Tags: Java architecture

Posted by subcool on Sat, 21 May 2022 20:48:37 +0300