深入剖析tomcat之一个简单的web服务器

本文涉及的产品
云解析 DNS,旗舰版 1个月
云解析DNS,个人版 1个月
全局流量管理 GTM,标准版 1个月
简介:

这个简单的web服务器包含三个类

  • HttpServer
  • Request
  • Response

在应用程序的入口点,也就是静态main函数中,创建一个HttpServer实例,然后调用其await()方法。顾名思义,await方法会在制定的端口上等待http请求,并对其进行处理,然后发送相应的消息回客户端。在接收到命令之前,它会一直保持等待的状态。

  • HttpServer类

package simpleHttpServer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
    
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator
            + "webroot";
    
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    
    private boolean shudown = false;
    
    public static void main(String[] args){
        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);
        }
        
        while(!this.shudown){
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            
            try{
                
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();
                
                Request request = new Request(input);
                request.parse();
                
                Response response = new Response(output);
                response.setRequest(request);
                response.sendStaticResource();
                
                socket.close();
                
                this.shudown = request.getUri().equals(SHUTDOWN_COMMAND);
                
            }
            catch (Exception e){
                e.printStackTrace();
                continue;
            }
        }
        
    }
        
}

这个简单的web服务器,可以处理指定目录中的静态资源请求;用WEB_ROOT表示制定的目录

public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";

这里是指当前目录下的webroot文件夹下面的资源。
我们通过在游览器中输入这样的内容,进行资源的请求:
http://127.0.0.1:8080/index.html

  • Request类
    Request类表示一个Http请求,可以传递InputStream对象来创建Request对象,调用InputStream对象的read进行Http请求数据的读取。

package simpleHttpServer;

import java.io.InputStream;

public class Request {
    private InputStream input;
    private String uri;
    
    public Request(InputStream input){
        this.input = input;
    }
    
    public void parse(){
        StringBuffer request = new StringBuffer(2048);
        
        int i;
        byte[] buffer = new byte[2048];
        try{
            i = input.read(buffer);
        }
        catch (Exception e){
            e.printStackTrace();
            i = -1;
        }
        
        for(int j=0;j<i;j++){
            request.append((char)buffer[j]);
        }
        
        System.out.print(request.toString());
        this.uri = this.parseUri(request.toString());
        
    }
    
    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 this.uri;
    }
    
}

Request类最重要的两个函数是parse和ParseUri;parse()方法会调用私有方法parseUri来解析HTTP请求的uri,初次之外,并没有做太多的工作。parseuri会将解析的URI存储在变量uri中。

我们以 http://127.0.0.1:8080/index.html 请求为例,HTTP请求的请求行为
GET /index.html HTTP/1.1
parse()方法从传入的Request对象的InputStream对象中读取整个字节流,并且将字节数组存入缓冲区。然后用缓存区的数组初始化StringBuffer对象request。 这样再解析StringBuffer就可以解析到Uri。

*Response类
Response类表示Http相应。其定义如下


package simpleHttpServer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response {
    
    private static final int BUFFER_SIZE = 1024;
    private Request request;
    private OutputStream output;
    
    public Response(OutputStream output){
        this.output = output;
    }
    
    public void setRequest(Request request){
        this.request = request;
    }
    
    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{
                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){
            e.printStackTrace();
        }
        finally{
            if(fis != null){
                fis.close();
            }
        }
        
    }
    
    
}

使用OutputStream和Request来初始化Reponse,Response比较简单,得到Request的Uri,然后读取对应的file,如果file存在,则将file中的数据读取到缓存中,并且发送给游览器;如果file不存在,那么就发送

"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>";

错误信息给游览器。

我们在eclipse中将代码跑起来,在游览器中输入
http://127.0.0.1:8080/index.html

99794-20160411224612598-1147416639.png

http://127.0.0.1:8080/index.php
99794-20160411224626160-2089546678.png

一个简单的额web服务器就跑起来了!


相关文章
|
6天前
|
弹性计算 数据库 数据安全/隐私保护
阿里云服务器真香宝典之Calibre-Web个人图书馆云端部署
在阿里云ECS(2核2G,SSD40G,3M带宽)上,安装Ubuntu 22.04,然后配置Docker和FTP。创建 `/config` 和 `/books` 目录,设置权限,开放端口,拉取 `johngong/calibre-web` Docker镜像,以`calibre-web`命名容器,映射端口,配置环境变量,挂载卷,确保重启策略。本地安装Calibre客户端,上传metadata.db到服务器。在Calibre-web服务端配置数据库,启用上传权限,修改管理员账户信息。完成配置后,开始上传电子书并进行阅读。
82 2
阿里云服务器真香宝典之Calibre-Web个人图书馆云端部署
|
2天前
|
监控 安全 应用服务中间件
如何搭建高效的Web服务器:技术指南与实践
【7月更文挑战第24天】搭建一个高效的Web服务器需要综合考虑多个方面,包括选择合适的操作系统、安装合适的Web服务器软件、进行配置优化、加强安全防护以及实施性能监控。通过不断地优化和调整,可以确保Web服务器在高负载下仍能保持稳定和高效的运行,为用户提供优质的访问体验。
|
6天前
|
Java Linux 应用服务中间件
Windows和Linux的最佳Web服务器
【7月更文挑战第20天】Windows和Linux的最佳Web服务器
19 3
|
7天前
|
存储 开发框架 安全
如何选择合适的Web服务器?
【7月更文挑战第19天】如何选择合适的Web服务器?
20 2
|
7天前
|
JavaScript Java 应用服务中间件
Web服务器的发展历程?
【7月更文挑战第19天】Web服务器的发展历程?
16 2
|
7天前
|
存储 缓存 监控
Web服务器
【7月更文挑战第19天】Web服务器
15 2
|
13天前
|
网络协议 安全 Python
我们将使用Python的内置库`http.server`来创建一个简单的Web服务器。虽然这个示例相对简单,但我们可以围绕它展开许多讨论,包括HTTP协议、网络编程、异常处理、多线程等。
我们将使用Python的内置库`http.server`来创建一个简单的Web服务器。虽然这个示例相对简单,但我们可以围绕它展开许多讨论,包括HTTP协议、网络编程、异常处理、多线程等。
|
21天前
|
前端开发 Java 应用服务中间件
C/S和B/S架构以及Web服务器
C/S和B/S架构以及Web服务器
21 0
|
3天前
|
弹性计算 运维 安全
阿里云ecs使用体验
整了台服务器部署项目上线
|
1天前
|
存储 弹性计算 固态存储
租赁云服务器多少钱一年?阿里云价格确实优惠!
阿里云服务器价格优惠多样,适合不同需求。2024年最新优惠中,轻量应用服务器2核2G3M带宽一年82元(约6.8元/月),新老用户均可享受99元一年的2核2G3M带宽ECS经济型e实例。企业用户专享2核4G5M带宽ECS u1实例199元一年。4核16G10M带宽游戏服务器70元/月,8核32G10M带宽160元/月。此外,还有GPU服务器等多种配置可选。续费优惠根据时长不同,最长可达3折。带宽和存储也有多种价格方案。具体详情和最新优惠请访问阿里云官网。
租赁云服务器多少钱一年?阿里云价格确实优惠!