Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize static resource server by hands

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article will give you a detailed explanation on how to implement a static resource server. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Introduction

A simple static resource server is realized by using socket programming of java, which can respond to static resources.

There are two versions of the source code in this article. The first version, called Server_v1, implements a simple socket server that helps readers recall socket programming. The second version is called Server_v2, which is an improvement of the first version, gives the idea of improvement and makes the necessary encapsulation so that it can respond to static resources such as css, html, jpg and so on.

Version one

This version implements a simple socket server that can return the corresponding page to the request of the browser.

The source code is as follows:

Package mytomcat_v1;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Date;public class Server_V1 {public static void main (String [] args) {ServerSocket serverSocket = null; Socket client = null; try {serverSocket = new ServerSocket (9999) While (true) {client = serverSocket.accept (); InputStream in = client.getInputStream (); byte [] buff = new byte [1024]; int len = in.read (buff) If (len > 0) {String msg = new String (buff, 0, len); System.out.println ("= =" + msg+ "="); OutputStream out = client.getOutputStream (); StringBuffer sb = new StringBuffer () Sb.append ("HTTP/1.1 200 OK\ n"); sb.append ("Content-Type: text/html; charset=UTF-8\ n"); sb.append ("\ n") String html= "sell pancakes" Xiaoqu often sells pancakes in "+" + new Date () + "+"; sb.append (html) Out.write (sb.toString (). GetBytes ()); out.flush (); out.close ();} catch (Exception e) {}

As shown in the following figure, open a chrome browser and type in the navigation bar

Http:

Display as shown in the following figure

The console output is shown in the following figure

= GET / docs/index.html HTTP/1.1Host: localhost:9999Connection: keep-aliveUpgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10 / 13 / 2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9= version 2

This version is optimized on the basis of version 1 so that it can respond effectively to static resources

Step one

Take a look at the first part of code optimization, as shown in the following figure

The part of the red box can be understood as processing the request information pair, so we mimic Tomcat to construct a HttpRequst to handle this logic.

In addition, we need to respond to static resources, so we need to get the static resource address of the input, that is, the contents of the following section.

The code to get the above red box request address content is as follows

Uri = msg.substring (msg.indexOf ("/"), msg.indexOf ("HTTP/1.1")-1)

To sum up, we have the HttpRequest class as follows

Package mytomcat_v2;import java.io.IOException;import java.io.InputStream;public class HttpRequest {private String uri; public String getUri () {return uri;} public HttpRequest (InputStream in) throws IOException {resolverRequest (in);} private void resolverRequest (InputStream in) throws IOException {byte [] buff = new byte [1024]; int len = in.read (buff) If (len > 0) {String msg = new String (buff, 0, len); System.out.println ("=" + msg + "="); uri = msg.substring (msg.indexOf ("/"), msg.indexOf ("HTTP/1.1")-1);} else {System.out.println ("bad Request!") Step 2

Then there is the second part of code optimization, as shown in the following figure

The above red box mainly responds to the output information, and we construct a HttpResponse object to encapsulate this part of the logic by imitating tomcat.

In addition, we get the path of the resource file requested by the user, and find the corresponding static file according to that path. Write the file to the file stream and output.

So, we have a HttpResponse object like this

Package mytomcat_v2;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;public class HttpResponse {private OutputStream os = null; public HttpResponse (OutputStream os) {this.os = os;} public void writerFile (String path) throws IOException {FileInputStream fileInputStream = new FileInputStream (path); byte [] buff = new byte [1024]; int len = 0; StringBuffer sb = new StringBuffer () Sb.append ("HTTP/1.1 200 OK\ n"); sb.append ("Content-Type: text/html; charset=UTF-8\ n"); sb.append ("\ n"); os.write (sb.toString (). GetBytes ()); while ((len = fileInputStream.read (buff))! =-1) {os.write (buff, 0, len) } fileInputStream.close (); os.flush (); os.close ();}} step 3

Next, let's build the test class, and before building it, let's find some static resource files. The author goes directly to apache's official website to download tomcat, and then goes to the following directory to copy static resource files.

Apache-tomcat-8.5.28/webapps/docs

Copy the entire docs folder to the root of your project

Apache-tomcat-8.5.28/webapps/ROOT/favicon.ico

Copy the favicon.ico picture to your root directory

The structure of static resources in your project is shown in the following figure

Now go to our Server_V2 code.

Package mytomcat_v2;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Date;public class Server_V2 {public static void main (String [] args) {ServerSocket serverSocket = null; Socket client = null; try {serverSocket = new ServerSocket (9999) While (true) {client = serverSocket.accept (); InputStream in = client.getInputStream (); HttpRequest request = new HttpRequest (in); String requestUri = request.getUri (); OutputStream os = client.getOutputStream () HttpResponse response = new HttpResponse (os); response.writerFile (requestUri.substring (1)); client.close ();} catch (Exception e) {e.printStackTrace ();}

The test results are as follows:

Enter in the browser

Http:

The effect is as follows

You will be surprised to find that the style is not recognized, so we modify part of the logic of the response header.

Set

Sb.append ("HTTP/1.1 200 OK\ n"); sb.append ("Content-Type: text/html; charset=UTF-8\ n"); sb.append ("\ n")

Partially modified to

If (path.endsWith ("css")) {sb.append ("HTTP/1.1 200 OK\ n"); sb.append ("Content-Type: text/css; charset=UTF-8\ n"); sb.append ("\ n");} else {sb.append ("HTTP/1.1 200 OK\ n"); sb.append ("Content-Type: text/html") Charset=UTF-8\ n "); sb.append ("\ n ");}

Continue to start the test, and the results are as follows

Has been able to display normally.

On how to achieve static resource server to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report