一个web服务器是网络应用中最基础的环节。

构建需要理解三个内容:

1.http协议

2.socket类

3.服务端实现原理

1.1 HTTP
 http请求
 一般一个http请求包括以下三个部分:
 1 请求方法,如get,post
 2 请求头
 
3 实体

1.2http响应
与http请求类似,http响应也包括三个部分
1 协议-状态码-描述
2 响应头
3 响应实体段

2.Socket

2.1不同的应用程序可以通过套接字发送或接受字节流。java中提供了Socket类来实现这个功能。

2.2光靠Socket类还是不能够实现我们构建一个服务器应用程序的功能的,因为服务器必须时刻待命,因此java里面提供了ServerSocket类来处理等待来自客户端的请求,当ServerSocket接受到了来自客户端的请求之后,它就会创建一个实例来处理与客户端的通信。

3.实现原理

3.1构建一个封装请求信息的类requst,一个响应请求的类response,还要有一个主程序httpServer来处理客户端来的请求

下面是一个requst类,主要处理uri

 1 package com.lwq;
 2
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5
 6 /**10  * 将浏览器发来的请求信息转化成字符和截取url
11  */
12 public class Request {14     //输入流
15     private InputStream input;
16     //截取url,如http://localhost:8080/index.html ,截取部分为 /index.html
17     private String uri;
18     public Request(InputStream inputStream){
19         this.input = inputStream;
20     }
22     public InputStream getInput() {
23         return input;
24     }
25     public void setInput(InputStream input) {
26         this.input = input;
27     }
28     public String getUri() {
29         return uri;
30     }
31     public void setUri(String uri) {
32         this.uri = uri;
33     }
35     //从套接字中读取字符信息
36     public void parse(){38             StringBuffer request = new StringBuffer(2048);
39             int i = 0;
40             byte[] buffer = new byte[2048];
41
42             try {
43                 i = input.read(buffer);
44             } catch (IOException e) {
45                 // TODO Auto-generated catch block
46                 e.printStackTrace();
47                 i = -1;
48             }
49             for(int j = 0;j<i;j++){
50                     request.append((char)(buffer[j]));//拼接请求字符串
51             }
52             System.out.println(request.toString());
53             uri = parseUri(request.toString());//截取url,存入uri字段
54             }
55     //截取请求的url
56     private String parseUri(String requestString){58         int index1 = 0;
59         int index2 = 0;
60         index1 = requestString.indexOf(' ');
61         if(index1!=-1){
62             index2 = requestString.indexOf(' ',index1+1);
63             if(index2>index1){
64                 return requestString.substring(index1+1,index2);
65             }
66         }
68         return null;
69     }
74     }

下面是封装了响应请求的类response,用于返回文件或数据

 1 package com.lwq;
 2
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.IOException;
 7 import java.io.OutputStream;
 8 import java.io.PrintWriter;
 9
10 /**13  * 类说明 根据相应信息返回结果
14  */
15 public class Response {
16
17     private static final int BUFFER_SIZE = 1024;
18     Request request;
19     OutputStream output;
20     public Response(OutputStream output){
21         this.output = output;
22     }
23
24     public void sendStaticResource() throws IOException{26         byte[] bytes = new byte[BUFFER_SIZE];
27         FileInputStream fis = null;
29         File file = new File(HttpServer.WEB_ROOT,request.getUri());
30         if(file.exists()){
31             try {
32                 fis = new FileInputStream(file);
33                 int ch = fis.read(bytes,0,BUFFER_SIZE);
34                 while(ch != -1){
35                     output.write(bytes,0,ch);//将文件的一部分写入流
36                     ch = fis.read(bytes,0,BUFFER_SIZE);
37                 }
38
39             } catch (FileNotFoundException e) {
40                 // TODO Auto-generated catch block
41                 e.printStackTrace();
42             }catch(IOException e){
43                 e.printStackTrace();
44             }finally{
45                 if(fis !=null){
46                     fis.close();
47                 }
48             }
50         }else{
51             //找不到文件
52              String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
53      "Content-Type: text/html\r\n" +
54      "Content-Length: 23\r\n" +
55      "\r\n" +
56      "
57 File Not Found
58 ";
59              try {
60                 output.write(errorMessage.getBytes());
61                 output.flush();
62             } catch (IOException e) {
63                 // TODO Auto-generated catch block
64                 e.printStackTrace();
65             }
66         }
67     }
68     public Request getRequest() {
69         return request;
70     }
71     public void setRequest(Request request) {
72         this.request = request;
73     }
74     public OutputStream getOutput() {
75         return output;
76     }
77     public void setOutput(OutputStream output) {
78         this.output = output;
79     }
80     public static int getBUFFER_SIZE() {
81         return BUFFER_SIZE;
82     }
86 }

主程序:

 1 package com.lwq;
 2
 3 import java.io.File;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.InetAddress;
 7 import java.net.ServerSocket;
 8 import java.net.Socket;
 9
10 /**13  * 类说明
14  */
15 public class HttpServer {17     /**
18      * @param args
19      */
20
21     //WEB_ROOT是服务器的根目录
22     public static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"webroot";
23
24     //关闭的命令
25     private static final String SHUTDOWN_COMMAND= "/SHUTDOWN";
26
27     public static void main(String[] args) {
28         // TODO Auto-generated method stub
29         HttpServer server = new HttpServer();
30         server.await();
31
32     }
33     public void await(){
34         ServerSocket serverSocket = null;
35         int port = 8080;
36         try {
37             serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
38             while(true)
39             {
40                 try {
41             Socket socket = null;
42             InputStream input = null;
43             OutputStream output = null;
44             socket = serverSocket.accept();
45             input = socket.getInputStream();
46             output = socket.getOutputStream();
47             //封装request请求
48             Request request = new Request(input);
49             request.parse();
50             //封装response对象
51             Response response = new Response(output);
52             response.setRequest(request);
53             response.sendStaticResource();
54             socket.close();
55                 } catch (Exception e) {
56                     // TODO Auto-generated catch block
57                     e.printStackTrace();
58                     continue;
59                 }
61             }
62         } catch (Exception e) {
63             // TODO Auto-generated catch block
64             e.printStackTrace();
65         }
69     }
72 }

运行httpServer,在浏览器中打下http://localhost:8080/index.jsp,就能看到服务器响应的结果了。

侵删。

转载于:https://www.cnblogs.com/xianerwonder/p/5710351.html

自己实现一个简易web服务器相关推荐

  1. PHP服务器脚本实例,Shell脚本实现的一个简易Web服务器例子分享_linux shell

    这篇文章主要介绍了Shell脚本实现的一个简易Web服务器例子分享,本文实现的Web服务器非常简单实用,可以在你不想安装nginx.apache等大型WEB服务器时使用,需要的朋友可以参考下 假设你想 ...

  2. node.js搭建简易Web服务器

    node.js搭建简易Web服务器 node.js简介 Node.js 是一个基于V8引擎的JavaScript 运行环境. V8 是为Google Chrome 提供支持的 JavaScript 引 ...

  3. 手写简易WEB服务器

    手写简易WEB服务器 今天我们来写一个类似于Tomcat的简易服务器.可供大家深入理解一下tomcat的工作原理,本文仅供新手参考,请各位大神指正! 首先我们要准备的知识是: Socket编程 HTM ...

  4. 【Python】快速创建一个简易 HTTP 服务器(http.server)

    引言 http.server 是 socketserver.TCPServer 的子类,它在 HTTP 套接字上创建和监听,并将请求分派给处理程序.本文是关于如何使用 Python 的 http.se ...

  5. [翻译]深入理解Tornado——一个异步web服务器

    本人的第一次翻译,转载请注明出处:http://www.cnblogs.com/yiwenshengmei/archive/2011/06/08/understanding_tornado.html ...

  6. 从源码开始编译一个带有WEB服务器功能的小型LINUX(下)

    上接:从源码开始编译一个带有WEB服务器功能的小型LINUX(上) 七.为新构建的ToyLinux启用虚拟控制台 这个可以通过宿主机来实现,也可以直接启动刚构建成功的小Linux进行配置.我们这里采用 ...

  7. java使用socket实现一个多线程web服务器

    全栈工程师开发手册 (作者:栾鹏) java教程全解 java使用socket实现一个多线程web服务器 除了服务器类,还包括请求类和响应类 请求类:获取客户的HTTP请求,分析客户所需要的文件 响应 ...

  8. 一个基于Web服务器的PoW区块链案例

    一个基于web服务器的PoW案例 一.安装第三方库 go get github.com/davecgh/go-spew/spew 这个库的功能是在命令行格式化输出内容. go get github.c ...

  9. 用原生Node实现一个静态web服务器

    之前一直用过Apache nginx等静态web服务器. 但强大的node.js本身就能作为独立的web服务器,不依赖与Apache  nginx 下面我们看看怎么用Node去写一个静态服务器吧 首先 ...

  10. TinyWS —— 一个C++写的简易WEB服务器(三)

    写在前面 代码已经托管在 https://git.oschina.net/augustus/TinyWS.git 可以用git clone下来.由于我可能会偶尔做一些修改,不能保证git 库上的代码与 ...

最新文章

  1. 【java】过滤器filter的使用
  2. webSocket浏览器握手不成功(解决)
  3. JQuery实现父级选择器(广告实现)
  4. HD 2602 Bone Collector (0-1背包)
  5. c语言用hash方式数组去重,js数组去重的hash方法
  6. 计算机高新办公软件应用,OFFICEXP全国计算机信息高新技术考试办公软件应用
  7. z-index的学习整理转述
  8. 【博客项目】—Joi(八)
  9. 华南理工大学811信号与系统真题
  10. C语言笔记 · ASCII码表
  11. MySQL功能大全(细品)
  12. 360随身wifi搭建无线热点
  13. 闪马智能+兑观科技|视频智能解析联合实验室揭牌成立
  14. java银行面试题目及答案,顺利拿到offer
  15. Python安装教程-手把手教你安装
  16. 南阳理工ACM 题4《ASCII码排序》
  17. Python批量提取Excel文件中文本框组件里的文本
  18. WF100DPZ 1BG S6 DT数字压力传感器
  19. SpringSecurity(安全)
  20. FFmpeg 命令详解

热门文章

  1. MathType中公式不对齐怎么办
  2. Laravel 速记表
  3. ajax基本概念,方法
  4. 一个PHP程序员应该掌握的10项技能!【更新】
  5. 看好你的数据库连接字符串!
  6. 基础训练 龟兔赛跑预测
  7. mixins,generics(ApiView)
  8. 玉伯 对 前端的 金玉良言
  9. LeetCode : Intersection of Two Linked Lists
  10. JavaScript_8_比较,条件语句