Client requests server communication, Web programming development basis

Keywords: Java socket Programming network

I haven't seen you for a long time. I miss you so much.

The article I published earlier has finished the primary stage of Java. Next, Xiaole will continue to talk about Java intermediate stage - Java Web.

First of all, let's take a look at the knowledge that the Java Web phase focuses on:

  • Understand C/S and B/S structural modes
  • Understanding how Web applications work
  • Implement the first Servlet program
  • Understand the internal workflow of the program
  • Master the basic configuration of web.xml

In this article, we will learn the fundamentals of web development.

 

1. Simple communication

Reviewing Socket programming gives us the greatest feeling that data can be transmitted between multiple computers, which is the beginning and foundation of network programming. Through the client requesting server-side communication, we can intuitively understand Web programming.

Server

/**
 * Server side, receiving client request and giving simple response
 * @author Administrator
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //1,Create server, specify port ServerSocket(int port)
        ServerSocket socket=new ServerSocket(8888);
        //2,Receive client connection
        Socket client=socket.accept();
        System.out.println("******************");
        //Get the input stream of data
        InputStream is=client.getInputStream();
        //Use character cache stream
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        String msg="";
        while((msg=br.readLine())!=null){
            System.out.println(msg);
        }
        br.close();
    }
}
//Original lebit

 

Client

/**
 * Client: send request to server and send simple message
 * @author Administrator
 */
public class Client {
    public static void main(String[] args) throws UnknownHostException, IOException {
        //Create client     Server must be specified+port    
        Socket client=new Socket("localhost",8888);
        //send message    Request resources
        //Get send stream
        OutputStream os=client.getOutputStream();
        BufferedWriter br=new BufferedWriter(new OutputStreamWriter(os));
        //Write message, send content
        String msg="hello I need some source";
        br.write(msg);
        br.close();
    }
}

 

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

1) need a server: wait to be requested, need to expose ip and port

2) need a client: initiate the request actively and know the ip and port of the server

3) communication rules (Protocol): TCP/IP protocol

ip is used to locate the computer; port number (locator) is used to identify the logical address of the process and the flag of different processes; effective port: 0 ~ 65535, of which 0 ~ 1024 is used or reserved by the system. It is recommended to use more than 1024 ports in the development.

 

2. Different requests

Client

package com.shsxt.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
/**
 * 
 * @author Lj
 *
 * Client
 */
public class Client {
    public static void main(String[] args) throws IOException {
        //  By default SocketImpl Create an unconnected socket
        Socket socket = new Socket();
        //Such implementation 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

package com.shsxt.socket;

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

/**
 * 
 * @author Lj
 * Server side
 * public class ServerSocketextends Object: This class implements the server socket. The server socket waits for the request to come in over the network. It performs certain operations based on the request and may then return results to the requester. 
 */
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()   Listen and accept 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();
    }
}

 

3. Complex request

Client

package com.shsxt.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
/**
 * @author Lj
 * Client
 */
public class Client {
    public static void main(String[] args) throws IOException {
        //  By default SocketImpl Create an unconnected socket
        Socket socket = new Socket();
        //Such implementation 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 response, display results
        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

package com.shsxt.socket;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * @author Lj Server public class ServerSocketextends
 *         Object: This class implements the server socket. The server socket waits for the request to come in over the network. It performs certain operations based on the request and may then return results to the requester.
 */
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() Listen and accept 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 as 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")) {
            // According to the requested information, construct the processed class
            MyServlet s1 = new ServletMoney();
            s1.service(request, response);
            // adopt client Respond to the client
            os.write("here's the money".getBytes());
            os.flush();
        } else if (reqStr.equals("time")) {
            // According to the requested information, construct the processed class
            MyServlet s2 = new ServletTime();
            s2.service(request, response);
            // adopt client Respond to the client
            os.write("you have somuch time".getBytes());
            os.flush();
        }
        client.close();
        server.close();
    }
}
/*
 * I'm a person with requirements. The resource you requested must be a class function that meets my requirements: prevent confusion and facilitate calling
 * This is my standard
 */
interface MyServlet {
    void service(MyRequest req, MyResponse resp);
}
class ServletMoney implements MyServlet {
    /*
     * @see com.shsxt.socket.MyServlet#service(com.shsxt.socket.MyRequest)
     */
    @Override
    public void service(MyRequest req, MyResponse resp) {
        // Do what the output can do
    }
}
class ServletTime implements MyServlet {
    /*
     * @see com.shsxt.socket.MyServlet#service(com.shsxt.socket.MyRequest)
     */
    @Override
    public void service(MyRequest req, MyResponse resp) {
        // Do what the output can do
    }
}
/*
 * Request information is encapsulated in the object according to the rules
 */
class MyRequest {
}
class MyResponse {
}

 

With more and more complex customer needs, more and more functions are needed, and more and more requests need to be processed on our server side. We need to distinguish different requests, extract request data according to different requests, allocate and calculate resources, and deal with them logically. Finally, we need to respond to the client, which makes the server-side code more and more complex. Now it's getting more and more difficult.

According to the past experience, the two sides only need to follow certain rules to communicate, so they can know the meaning of each part of the data clearly. So there is an application protocol (HTTP protocol later), which stipulates the rules of communication between the server and the client.

The client requests the server and the server responds to the client according to the fixed rules. Then the operation of receiving the request and the corresponding data can be fixed and handed over to a specific piece of code for execution, so as to reduce the code amount of the server, so the next server appears.

4. Appearance of server

When the resources requested by the client are more and more abundant and the requirements are more and more complex, the core of the program should be put on solving the business and calculating the response data, so it appears that the server uniformly receives the client processing and distributes it to different resources, which are processed by each resource, and the final result is sent to the server for response.

From the above description, we can see that the server is only responsible for receiving the request, distributing the request, and finally carrying out the corresponding fixed framework for the acquired data. As for how to calculate the data, we have to write (fill) code according to the specific business requirements. The server can be prepared without business requirements. Now there are many servers on the market, including Tomcat, JBOOS, IBM's WebSphere, BEA's WebLogic and Apache.

Well, that's the basis of web development. The next article will introduce Java Web and C/S and B/S architecture. Please pay attention to le byte.~~~~

Posted by j0sh on Fri, 18 Oct 2019 01:42:25 -0700