一个简单的Web服务器

简介:

HttpServer, Request, Response
Java代码

package com.iteye.wely.server;  
  
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;  
  
/** 
 * Created by shenhongxi on 16/3/21. 
 */  
public class HttpServer {  
  
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "ixhong-tomcat-web/src/main/webapp";  
  
    private static final String SHUTDOWN_COMMAND = "SHUTDOWN";  
  
    private boolean shutdown = false;  
  
    public static void main(String[] args) {  
        HttpServer server = new HttpServer();  
        System.out.println(WEB_ROOT);  
        server.await();  
    }  
  
    private void await() {  
        ServerSocket serverSocket = null;  
        int port = 8080;  
        try {  
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));  
            System.out.println("Server started!");  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.exit(1);  
        }  
  
        while (!shutdown) {  
            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();  
  
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);  
            } catch (Exception e) {  
                e.printStackTrace();  
                continue;  
            }  
        }  
    }  
}  
Java代码  收藏代码
package com.iteye.wely.server;  
  
import java.io.IOException;  
import java.io.InputStream;  
  
/** 
 * Created by shenhongxi on 16/3/21. 
 */  
public class Request {  
  
    private InputStream input;  
  
    private String uri; // 性能考虑,用byte[]  
  
    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 (IOException e) {  
            e.printStackTrace();  
            i = -1;  
        }  
        for (int j = 0; j < i; j++) {  
            request.append((char) buffer[j]);  
        }  
        System.out.println(request.toString());  
        uri = parseUri(request.toString());  
    }  
  
    private String parseUri(String requestStr) {  
        // GET /index.html HTTP/1.1  
        // Accept: text/plain; text/html  
        // ...  
        int index1 = requestStr.indexOf(' ');  
        int index2;  
        if (index1 != -1) {  
            index2 = requestStr.indexOf(' ', index1 + 1);  
            if (index2 > index1) {  
                return requestStr.substring(index1 + 1, index2);  
            }  
        }  
        return null;  
    }  
  
    public String getUri() {  
        return uri;  
    }  
}  
Java代码  收藏代码
package com.iteye.wely.server;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
  
/** 
 * Created by shenhongxi on 16/3/21. 
 */  
public class Response {  
  
    private static final int BUFFER_SIZE = 1024;  
  
    Request request;  
  
    OutputStream output;  
  
    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 errorMsg = "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(errorMsg.getBytes());  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (fis != null) {  
                fis.close();  
            }  
        }  
    }  
  
    public Response(OutputStream output) {  
        this.output = output;  
    }  
  
    public void setRequest(Request request) {  
        this.request = request;  
    }  
}

原文链接:[]

相关文章
|
1月前
|
存储 缓存 网络协议
Web客户/服务器程序
Web客户/服务器程序
|
1月前
|
编译器 开发工具 C语言
交叉编译器环境配置与boa嵌入式web服务器移植问题
交叉编译器环境配置与boa嵌入式web服务器移植问题
46 0
|
2月前
|
存储 资源调度 应用服务中间件
浅谈本地开发好的 Web 应用部署到 ABAP 应用服务器上的几种方式
浅谈本地开发好的 Web 应用部署到 ABAP 应用服务器上的几种方式
32 0
|
2月前
|
网络协议 Shell 网络安全
实验目的1.编译安装httpd2.优化路径3.并将鲜花网站上传到web服务器为网页目录4.在客户机访问网站http://www.bdqn.com
实验目的1.编译安装httpd2.优化路径3.并将鲜花网站上传到web服务器为网页目录4.在客户机访问网站http://www.bdqn.com
167 0
|
2月前
|
前端开发 应用服务中间件 nginx
使用Docker快速搭建Web服务器Nginx
本文指导如何使用Docker快速搭建Nginx服务器。首先,通过`docker pull`命令获取Nginx镜像,然后以容器形式运行Nginx并映射端口。通过挂载目录实现本地文件与容器共享,便于自定义网页。使用`docker ps`检查运行状态,访问IP:8088确认部署成功。最后,介绍了停止、删除Nginx容器的命令,强调Docker简化了服务器部署和管理。
60 0
|
4天前
|
缓存 负载均衡 安全
深入探索Nginx高性能Web服务器配置与优化
【5月更文挑战第7天】本文深入探讨了Nginx的配置与优化,重点介绍了基础配置参数如`worker_processes`、`worker_connections`和`keepalive_timeout`,以及优化策略,包括使用epoll事件驱动模型、开启gzip压缩、启用缓存、负载均衡和安全配置。此外,还提到了性能调优工具,如ab、nginx-stats和nmon,以助于提升Nginx的性能和稳定性。
|
13天前
|
中间件 Go API
Golang深入浅出之-Go语言标准库net/http:构建Web服务器
【4月更文挑战第25天】Go语言的`net/http`包是构建高性能Web服务器的核心,提供创建服务器和发起请求的功能。本文讨论了使用中的常见问题和解决方案,包括:使用第三方路由库改进路由设计、引入中间件处理通用逻辑、设置合适的超时和连接管理以防止资源泄露。通过基础服务器和中间件的代码示例,展示了如何有效运用`net/http`包。掌握这些最佳实践,有助于开发出高效、易维护的Web服务。
27 1
|
15天前
|
机器学习/深度学习 数据挖掘 Python
使用Python实现简单的Web服务器
使用Python内置的http.server模块,本文演示了创建基本Web服务器的步骤。通过编写简单的代码,实现响应GET请求并返回“Hello, World!”。此外,还展示了如何扩展服务器功能,处理不同URL路径,如根路径和/about路径,并实现404错误页面。这个基础教程为理解HTTP服务器原理和Python网络编程入门提供了帮助。对于复杂Web应用,建议使用Flask或Django等高级框架。
|
17天前
|
负载均衡 监控 Unix
[AIGC] Nginx:一个高性能的 Web 服务器和反向代理
[AIGC] Nginx:一个高性能的 Web 服务器和反向代理
|
22天前
|
Apache
web服务器(Apache)访问日志(access_log)详细解释
web服务器(Apache)访问日志(access_log)详细解释