Communication in the development of the Web

  • A simple communication
  • Different request
  • Complex request

Welcome to pay attention to my B station account

B station account

If the content helps you, welcome everyone to like, favorites + attention

Learning exchange group

A case in field

1 Simple Communication

Reviewing Socket programming gives us the biggest feeling, is can carry on the data transmission between many computers, this is the beginning and foundation of network programming, through the client request server communication, intuitive understanding of Web programming.

Server

/** * server, which receives client requests and gives simple responses *@author Cushier
 *
 */
public class Server {
	
	public static void main(String[] args) throws IOException{
		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();
		// Input stream with buffered characters
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String msg = "";
		while((msg = br.readLine()) ! =null) { System.out.println(msg); } br.close(); }}Copy the code

Client

/** * client: sends a request to the server and a simple message *@author Cushier
 *
 */
public class Client {
	
	public static void main(String[] args) throws UnknownHostException, IOException {
		// Create client must specify server + port
		Socket client = new Socket("localhost".8888);
		// Send a message requesting resources
		// Get the output stream
		OutputStream os = client.getOutputStream();
		// Output the stream using buffered characters
		BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os));
		// Write out the message and send the content
		String msg = "Hello, I am Client, I need some resources"; br.write(msg); br.close(); }}Copy the code

Server console:

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

  1. Need a server: wait to be requested, need to expose the IP and port
  2. A client is required: initiates requests proactively and knows the IP address and port of the server
  3. Communication rules (protocol) : TCP/IP

IP is used to locate the computer; Port number (locator), used to identify the logical address of the process, the logo of different processes; Valid port: 0 65535, 0 1024 is reserved or used by the system. You are advised to use a port larger than 1024 during development.

2 Different Requests

Client

/** * client: send requests to the server, send different requests *@author Cushier
 *
 */
public class Client {
	
	public static void main(String[] args) throws IOException {
		// Create an unconnected socket with SocketImpl of the system default type
		Socket socket = new Socket();
		// This class implements the IP socket address (IP address + port number). It can also be a pair (host name + port number), in which case the host name will be attempted to resolve
		SocketAddress address = new InetSocketAddress("localhost".8898);
		// Connect this socket to the server and specify a timeout value. Or no timeout is specified
		socket.connect(address, 1000);
		OutputStream os = socket.getOutputStream();
		os.write("time".getBytes()); os.flush(); socket.close(); }}Copy the code

Server

/** * Public class ServerSocketextends Object: Implements server sockets. * The server socket waits for requests to come in over the network. * It performs some action based on the request and may then return the result to the requester. * *@author Cushier
 *
 */
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 for and accepts connections to this Socket.
		Socket client = server.accept();
		System.out.println("Received connection");

		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(); }}Copy the code

Picture archiving server console: [outside chain failure, the source station might be hotlinking prevention mechanism, proposed to directly upload picture preserved (img – S3qcLwv2-1599639352006) (raw.githubusercontent.com/Cushier/pic…)”

3 Complex Request

Client

/** * client **@author Cushier
 *
 */
public class Client {
	
	public static void main(String[] args) throws IOException {
		// Create an unconnected socket with SocketImpl of the system default type
		Socket socket = new Socket();
		// This class implements the IP socket address (IP address + port number). It can also be a pair (host name + port number), in which case the host name will be attempted to resolve
		SocketAddress address = new InetSocketAddress("localhost".8898);
		// Connect this socket to the server and specify a timeout value. Or no timeout is specified
		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(); }}Copy the code

Server

/** * server *@author Cushier
 *
 */
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 for and accepts connections to this Socket.
		Socket client = server.accept();
		System.out.println("Received connection");
		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 that is passed to the requesting class
		MyRequest request = new MyRequest();
		MyResponse response = new MyResponse();

		OutputStream os = client.getOutputStream();
		if (reqStr.equals("money")) {
			// From the requested information, construct the processing class
			MyServlet s1 = new ServletMoney();
			s1.service(request, response);
			// Return the result to the client through the client's response
			os.write("here's the money".getBytes());
			os.flush();
		} else if (reqStr.equals("time")) {
			// From the requested information, construct the processing class
			MyServlet s2 = new ServletTime();
			s2.service(request, response);
			// Return the result to the client through the client's response
			os.write("you have somuch time".getBytes()); os.flush(); } client.close(); server.close(); }}/* * I am a person with requirements, you request this resource must meet my requirements of the format of the class, function: to prevent chaos, convenient call this is my standard */
interface MyServlet {
	void service(MyRequest req, MyResponse resp);
}

class ServletMoney implements MyServlet {
	@Override
	public void service(MyRequest req, MyResponse resp) {
		// Do what you can}}class ServletTime implements MyServlet {
	@Override
	public void service(MyRequest req, MyResponse resp) {
		// Do what you can}}/* * Request information is regularly encapsulated in the object */
class MyRequest {}class MyResponse {}Copy the code

Picture archiving server console: [outside chain failure, the source station might be hotlinking prevention mechanism, proposed to directly upload picture preserved (img – HVaNN4Mn – 1599639352007) (raw.githubusercontent.com/Cushier/pic…)” Client console: Outside the chain picture archiving failure, the source station might be hotlinking prevention mechanism, Suggestions to upload images saved directly (img – uRJTm8ue – 1599639352008) (https://raw.githubusercontent.com/Cushier/picture/master/ 20190307152312.png)]

As customers demand more and more complex, the function of the need to more and more, our server to deal with the request of more and more, need to distinguish between different requests, also need to request data according to different requests are extracted, and the processing of the allocation of resources and the arithmetic and logic, at last you also need to response to the client, this makes the server-side code is more and more complicated, It’s getting harder.

Based on past experience, both parties can clearly know the meaning of each part of data only by following certain rules when they communicate. Therefore, the application protocol of the upper layer of the network (HTTP protocol later) has emerged to define the rules for the communication between the server and the client.

The client requests the server and the server responds to the client according to fixed rules, so the part of receiving the request and responding data can be fixed and assigned to a specific piece of code, thus reducing the amount of code on the server side, and hence the next server.

extension

The emergence of servers

When the client requests more and more rich resources, the demand is more and more complex, the core of the program should be placed on solving the business and computing response data, so the server uniformly receives the client data for processing and distributes it to different resources, processed by each resource, and finally the result is sent to the server for response.

TP protocol), specifying the rules for communication between the server and the client.

The client requests the server and the server responds to the client according to fixed rules, so the part of receiving the request and responding data can be fixed and assigned to a specific piece of code, thus reducing the amount of code on the server side, and hence the next server.

extension

The emergence of servers

When the client requests more and more rich resources, the demand is more and more complex, the core of the program should be placed on solving the business and computing response data, so the server uniformly receives the client data for processing and distributes it to different resources, processed by each resource, and finally the result is sent to the server for response.

As can be seen from the above description, the server is only responsible for receiving the request, distributing the request, and finally obtaining the corresponding fixed framework of the data, and how to calculate the data has to be written (populated) according to the specific business requirements. There are many servers on the market now. The most commonly used ones are: Tomcat, JBOOS, WebSphere of IBM, WebLogic of BEA and Apache, etc.