How Tomcat works之(一个简单的web服务器)
来源:互联网 发布:网络整合营销 编辑:程序博客网 时间:2024/05/21 23:24
一、描述
1、这里简单的描述一下web服务器的工作流程,从浏览器请求,到服务器的响应。
2、采用java中的serversocket类
3、需要的环境是 maven3.3.9,jdk1.8
二、实现
1、新建一个maven项目tomcat,目录如下
2、首先是用来接收请求的serversocket,他的作用是:接受浏览器的请求,并把请求数据封装给request,在调用response进行响应。代码如下
HttpServer.java
package ex01;import java.net.Socket;import java.net.ServerSocket;import java.net.InetAddress;import java.io.InputStream;import java.io.OutputStream;import java.io.IOException;import java.io.File;/** * * 负责接收请求 * 1、把请求的数据封装到request * 3、把request设置给response * 2、然后调用response进行相应 * */public class HttpServer { /** * 得到静态资源目录 */ public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot"; // shutdown command private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; // the shutdown command received private boolean shutdown = false; public static void main(String[] args) { System.out.println(WEB_ROOT); HttpServer server = new HttpServer(); server.await(); } public void await() { ServerSocket serverSocket = null; int port = 8080; try { serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); System.exit(1); } // Loop waiting for a request while (!shutdown) { Socket socket = null; InputStream input = null; OutputStream output = null; try { socket = serverSocket.accept(); input = socket.getInputStream(); output = socket.getOutputStream(); // create Request object and parse Request request = new Request(input); request.parse(); // create Response object Response response = new Response(output); response.setRequest(request); response.sendStaticResource(); // Close the socket socket.close(); //check if the previous URI is a shutdown command shutdown = SHUTDOWN_COMMAND.equals(request.getUri()); } catch (Exception e) { e.printStackTrace(); continue; } } }}
3、创建request类,他负责解析请求数据,并对其进行封装。
Request.java
package ex01;import java.io.InputStream;import java.io.IOException;/** * 1、负责解析请求的url * */public class Request { private InputStream input; private String uri; public Request(InputStream input) { this.input = input; } /** * 接受请求数据,转化为string */ public void parse() { // Read a set of characters from the socket StringBuffer request = new StringBuffer(2048); int i; byte[] buffer = new byte[2048]; try { i = input.read(buffer); } catch (IOException e) { e.printStackTrace(); i = -1; } for (int j=0; j<i; j++) { request.append((char) buffer[j]); } System.out.print(request.toString()); uri = parseUri(request.toString()); } /** * 查找第一个和第二个空格,并取出url * @param requestString * @return */ private String parseUri(String requestString) { int index1, index2; index1 = requestString.indexOf(' '); if (index1 != -1) { index2 = requestString.indexOf(' ', index1 + 1); if (index2 > index1) return requestString.substring(index1 + 1, index2); } return null; } public String getUri() { return uri; }}
4、之后是response响应类,他负责读取静态资源的信息,并把它返回给浏览器
Response.java
package ex01;import java.io.OutputStream;import java.io.IOException;import java.io.FileInputStream;import java.io.File;/* HTTP Response = Status-Line *(( general-header | response-header | entity-header ) CRLF) CRLF [ message-body ] Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF*//** * 响应 */public class Response { private static final int BUFFER_SIZE = 1024; Request request; OutputStream output; public Response(OutputStream output) { this.output = output; } /** * 设置request * @param request */ public void setRequest(Request request) { this.request = request; } /** * 1、找到对应的静态资源 * 2、读取数据 * 3、进行相应 * @throws IOException */ public void sendStaticResource() throws IOException { byte[] bytes = new byte[BUFFER_SIZE]; FileInputStream fis = null; try { File file = new File(HttpServer.WEB_ROOT, request.getUri()); if (file.exists()) { fis = new FileInputStream(file); int ch = fis.read(bytes, 0, BUFFER_SIZE); while (ch != -1) { output.write(bytes, 0, ch); ch = fis.read(bytes, 0, BUFFER_SIZE); } } else { // file not found String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + "\r\n" + "<h1>File Not Found</h1>"; output.write(errorMessage.getBytes()); } } catch (Exception e) { // thrown if cannot instantiate a File object System.out.println(e.toString()); } finally { if (fis != null) fis.close(); } }}
5、需要其运行还需要在根目录下创建一个webroot目录,这个目录根据你在httpServer中写的。然后在里面创建index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body>hello</body></html>
6、然后启动ie 由于谷歌不接受服务器返回的数据,所以使用的ie,输入以下地址
http://127.0.0.1:8080/index.html
7、效果如下
8、源码下载地址
https://gitee.com/lgr123/tomcat/tree/master/
阅读全文
0 0
- How Tomcat works之(一个简单的web服务器)
- 《How To Tomcat Works》-第一章:一个简单的Web服务器
- how tomcat works 读书笔记(一)----------一个简单的web服务器
- 《how tomcat works》第一章 构建一个简单的web服务器
- [How Tomcat Works]第1章 一个简单的Web服务器
- How Tomcat Works(Scala语言) 01 一个简单的Web服务器
- How tomcat works——1 一个简单的Web Server
- how tomcat works 读书笔记(二)----------一个简单的servlet容器
- 【How Tomcat Works】第一章——一个简易的java web服务实现(上)
- [How Tomcat Works]第2章 一个简单的Servlet容器
- How Tomcat Works(Scala语言) 02 一个简单的Servlet容器
- 《How To Tomcat Works》-第2章:一个简单的Servlet容器
- Tomcat-001-一个简单的web服务器
- How Tomcat works 之The Application 应用
- How Tomcat works 之 StandardWrapper 标准包装
- How Tomcat works之StandardContext 标准上下文
- How Tomcat works之 Host and Engine
- How Tomcat Works之ex01时序图
- LWLR 局部加权线性回归---Python实现
- 一位资深程序员大牛给予Java初学者的学习路线建议
- java编程思想笔记-并发之线程加入
- LinuxC简谈之字符串函数及其实现
- php链接mysql及mysqli深入透析
- How Tomcat works之(一个简单的web服务器)
- kafka 容器报内存不足异常(failed; error='Cannot allocate memory' (errno=12))
- 离线应用和本地存储
- 容器
- javascript中的this词法
- spring boot 下mybatis的mapper Could not autowire问题
- Mysql常用命令行集
- vue2.0 组件通信
- C语言指针变量作为函数参数