这个简单的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

http://127.0.0.1:8080/index.php

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

深入剖析tomcat之一个简单的web服务器的更多相关文章

  1. Tomcat剖析(一):一个简单的Web服务器

    Tomcat剖析(一):一个简单的Web服务器 1. Tomcat剖析(一):一个简单的Web服务器 2. Tomcat剖析(二):一个简单的Servlet服务器 3. Tomcat剖析(三):连接器 ...

  2. Tomcat学习笔记(一)一个简单的Web服务器

    内容为<深入剖析Tomcat>第一章重点,以及自己的总结,如有描述不清的,可查看原书. 一.HTTP协议: 1.定义:用于服务器与客户端的通讯的协议,允许web服务器和浏览器通过互联网进行 ...

  3. 《深度解析Tomcat》 第一章 一个简单的Web服务器

    本章介绍Java Web服务器是如何运行的.从中可以知道Tomcat是如何工作的. 基于Java的Web服务器会使用java.net.Socket类和java.net.ServerSocket类这两个 ...

  4. Tomcat源码学习记录--web服务器初步认识

    Tomcat作为开源的轻量级WEB服务器,虽然不是很适合某些大型项目,但是它开源,读其源代码可以很好的提高我们的编程功底和设计思维.Tomcat中用到了很多比较好的设计模式,其中代码风格也很值得我们去 ...

  5. 自己模拟的一个简单的web服务器

    首先我为大家推荐一本书:How Tomcat Works.这本书讲的很详细的,虽然实际开发中我们并不会自己去写一个tomcat,但是对于了解Tomcat是如何工作的还是很有必要的. Servlet容器 ...

  6. 一个简单的Web服务器-支持Servlet请求

    上接 一个简单的Web服务器-支持静态资源请求,这个服务器可以处理静态资源的请求,那么如何处理Servlet请求的呢? 判断是否是Servlet请求 首先Web服务器需要判断当前请求是否是Servle ...

  7. 一个简单的Web服务器-支持静态资源请求

    目标 实现一个简单的Web服务器,能够根据HTTP请求的URL响应对应的静态资源,如果静态资源不存在则响应404. HttpServer 使用ServerSocket实现的一个服务器,request根 ...

  8. 使用 Nodejs 搭建简单的Web服务器

    使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...

  9. 20145216 20145330 《信息安全系统设计基础》 实验五 简单嵌入式WEB 服务器实验

    20145216 20145330 <信息安全系统设计基础> 实验五 简单嵌入式WEB 服务器实验 实验报告封面 实验步骤 1.阅读理解源码 进入/arm2410cl/exp/basic/ ...

随机推荐

  1. 正在运行的android程序,按home键之后退回到桌面,在次点击程序图标避免再次重新启动程序解决办法

    正在运行的android程序,按home键之后退回到桌面,在次点击程序图标避免再次重新启动程序解决办法 例如:一个android程序包含两个Activity,分别为MainActivity和Other ...

  2. SSH学习笔记

    Struts2登录模块处理流程: 浏览器发送请求http://localhost/appname/login.action,到web应用服务器: 容器接收到该请求,根据web.xml的配置,服务器将请 ...

  3. 搭建Linux+Jexus+MariaDB+ASP.NET[LJMA]环境

    备注:,将我的博客内容整理成册,首先会在博客里优先发布,后续可能的话整理成电子书,主要从linux的最基础内容开始进入Linux的Mono开发方面的话题.本文是我整理博客内容的一篇文章. LJMA 是 ...

  4. Java多线程7:死锁

    前言 死锁单独写一篇文章是因为这是一个很严重的.必须要引起重视的问题.这不是夸大死锁的风险,尽管锁被持有的时间通常很短,但是作为商业产品的应用程序每天可能要执行数十亿次获取锁->释放锁的操作,只 ...

  5. MySQL5.7 新增配置

    1.log_timestamps 在5.7.2以后的版本中增加一个单独控制error log , general log,slow log的记录的时间,默认是UTC,需要配置成SYSTEM(本地时间) ...

  6. ASP.NET Web API自身对CORS的支持: EnableCorsAttribute特性背后的故事

    从编程的角度来讲,ASP.NET Web API针对CORS的实现仅仅涉及到HttpConfiguration的扩展方法EnableCors和EnableCorsAttribute特性.但是整个COR ...

  7. WCF学习之旅——第一个WCF示例(一)

    最近需要用到WCF,所以对WCF进行了解.在实践中学习新知识是最快的,接下来先做了一个简单的WCF服用应用示例. 本文的WCF服务应用功能很简单,却涵盖了一个完整WCF应用的基本结构.希望本文能对那些 ...

  8. 《Qt Quick 4小时入门》学习笔记3

    http://edu.csdn.net/course/detail/1042/14807?auto_start=1 Qt Quick 4小时入门 第八章:Qt Quick中的锚(anchors)布局 ...

  9. Linux线程体传递参数的方法详解

    传递参数的两种方法 线程函数只有一个参数的情况:直接定义一个变量通过应用传给线程函数. 例子 #include #include using namespace std; pthread_t thre ...

  10. DataBase异常状态:Recovery Pending,Suspect,估计Recovery的剩余时间

    一,RECOVERY PENDING状态 今天修改了SQL Server的Service Account的密码,然后重启SQL Server的Service,发现有db处于Recovery Pendi ...