功能完整的HTTP服务器

导语

这个一个功能完备的HTTP服务器。它可以提供一个完整的文档输,包括图像,applet,HTML文件,文本文件。它与SingleFileHttpServer非常相似,只不过它所关注的是GET请求的内容。它会根据GET请求的内容在自己的工作目录查找对应的资源,并将该资源返回给用户。这个服务是相当轻量级的。

主线程代码

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger; public class JHTTP {
//开启日志
private static final Logger logger = Logger.getLogger(JHTTP.class.getCanonicalName());
//线程数
private static final int NUM_THREAD = 50;
//默认主页
private static final String INDEX_FILE = "index.html";
//服务器工作目录
private final File rootDirectory;
//端口号
private final int port; /**
*
* @param _rootDirectory 工作目录
* @param _port 端口号
*/
public JHTTP(File _rootDirectory, int _port) {
if (!_rootDirectory.isDirectory())
throw new RuntimeException(_rootDirectory + "does not exist as a directory");
rootDirectory = _rootDirectory;
port = _port;
} /**
* 启动服务器
* @throws IOException
*/
public void start() throws IOException {
ExecutorService pool = Executors.newFixedThreadPool(NUM_THREAD);
try (ServerSocket server = new ServerSocket(port)) {
logger.info("Accepting connection on port" + server.getLocalPort());
logger.info("Document Root: " + rootDirectory);
while (true) {
try {
Socket request = server.accept();
pool.execute(new RequestProcessor(rootDirectory, INDEX_FILE, request));
} catch (IOException e) {
logger.warning("Error accepting connection");
}
}
}
} public static void main(String[] args) { //设置工作目录
File docroot;
try {
docroot = new File(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: java JHTTP docroot port");
return;
} //设置监听端口号
int port;
try {
port = Integer.parseInt(args[1]);
if (port < 0 || port > 65535) port = 8080;
} catch (RuntimeException e) {
port = 8080;
} try {
JHTTP webserver = new JHTTP(docroot, port);
webserver.start();
} catch (IOException e) {
logger.severe("Server cloud not start");
}
}
}

主线程代码比较简单,默认监听8080端口,将连接提交给工作线程来处理。

处理线程

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.Date;
import java.util.logging.Logger; public class RequestProcessor implements Runnable { private final static Logger logger = Logger.getLogger(RequestProcessor.class.getCanonicalName());
private File rootDirectory;
private String indexFileName = "index.html";
private Socket conn; public RequestProcessor(File _rootDirectory, String _indexFileName,
Socket _conn) {
if (_rootDirectory.isFile())
throw new IllegalArgumentException("rootDirectory muse be a directory, not a file");
rootDirectory = _rootDirectory;
indexFileName = _indexFileName;
conn = _conn;
} @Override
public void run() {
String root = rootDirectory.getPath();
try {
BufferedOutputStream raw = new BufferedOutputStream(conn.getOutputStream());
Writer out = new BufferedWriter(new OutputStreamWriter(raw, "utf-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String get = in.readLine();
if (get != null) {
logger.info(conn.getRemoteSocketAddress() + " " + get);
String[] pieces = get.split("\\s+");
String method = pieces[0];
String version = "";
if (method.equals("GET")) {
String fileName = pieces[1];
if (fileName.endsWith("/")) fileName += indexFileName;
String contentType = URLConnection.getFileNameMap().getContentTypeFor(root +fileName);
if (pieces.length > 2) {
version = pieces[2];
}
File theFile = new File(rootDirectory, fileName.substring(1, fileName.length()));
if (theFile.canRead() && theFile.getCanonicalPath().startsWith(root)) {
byte[] theData = Files.readAllBytes(theFile.toPath());
if (version.startsWith("HTTP/"))
sendHeader(out, "HTTP/1.1 200 OK", contentType, theData.length);
raw.write(theData);
raw.flush();
raw.close();
} else { //无法找到文件
String body = "<html><head><title>File not found</title></head><body>Error 404:文件未找到</body></html>";
if (version.startsWith("HTTP/"))
sendHeader(out, "HTTP/1.1 4O4 File Not Found", "text/html;charset=utf-8", body.getBytes("utf-8").length);
out.write(body);
out.flush();
out.close();
}
} else {
String body = "<html><head><title>File not found</title></head><body>Error 501:无法处理该请求</body></html>";
if (version.startsWith("HTTP/"))
sendHeader(out, "HTTP/1.1 5O1 Not Implemented", "text/html;charset=utf-8", body.getBytes("utf-8").length);
out.write(body);
out.flush();
out.close();
}
}
} catch (IOException e){
logger.warning("Error talking to " + conn.getRemoteSocketAddress());
} finally {
try {
conn.close();
} catch (IOException e) {}
}
} private void sendHeader(Writer out, String responseCode, String contentType, int length) throws IOException {
out.write(responseCode + "\r\n");
out.write("Date: " + new Date() + "\r\n");
out.write("Server: JHTTP 2.0\r\n");
out.write("Content-Type: " + contentType + "\r\n");
out.write("Content-Length: " + length + "\r\n\r\n");
out.flush();
}
}

在处理线程中处理客户端的请求,通过解析GET请求的资源从本地中查找对应的资源。如果没有找的则返回404错误

HTTPf服务器(3)的更多相关文章

  1. Apache是目前应用最广的Web服务器,PHP3是一种类似ASP的脚本语言

    一.如何获得软件? 获得这3个软件包的方法很多,目前大多数Linux分发都捆绑了这3个软件包,如RedHat.本文介绍的安装方法是基于从这些软件的官方站点上下载获得的软件包进行的,针对RedHat L ...

  2. App开发:模拟服务器数据接口 - MockApi

    为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现Moc ...

  3. 闰秒导致MySQL服务器的CPU sys过高

    今天,有个哥们碰到一个问题,他有一个从库,只要是启动MySQL,CPU使用率就非常高,其中sys占比也比较高,具体可见下图. 注意:他的生产环境是物理机,单个CPU,4个Core. 于是,他抓取了CP ...

  4. 闲来无聊,研究一下Web服务器 的源程序

    web服务器是如何工作的 1989年的夏天,蒂姆.博纳斯-李开发了世界上第一个web服务器和web客户机.这个浏览器程序是一个简单的电话号码查询软件.最初的web服务器程序就是一个利用浏览器和web服 ...

  5. SignalR系列续集[系列8:SignalR的性能监测与服务器的负载测试]

    目录 SignalR系列目录 前言 也是好久没写博客了,近期确实很忙,嗯..几个项目..头要炸..今天忙里偷闲.继续我们的小系列.. 先谢谢大家的支持.. 我们来聊聊SignalR的性能监测与服务器的 ...

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

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

  7. 通过ProGet搭建一个内部的Nuget服务器

    .NET Core项目完全使用Nuget 管理组件之间的依赖关系,Nuget已经成为.NET 生态系统中不可或缺的一个组件,从项目角度,将项目中各种组件的引用统统交给NuGet,添加组件/删除组件/以 ...

  8. 谈谈如何使用Netty开发实现高性能的RPC服务器

    RPC(Remote Procedure Call Protocol)远程过程调用协议,它是一种通过网络,从远程计算机程序上请求服务,而不必了解底层网络技术的协议.说的再直白一点,就是客户端在不必知道 ...

  9. 游戏服务器菜鸟之C#初探一游戏服务

    本人80后程序猿一枚,原来搞过C++/Java/C#,因为工作原因最后选择一直从事C#开发,因为读书时候对游戏一直比较感兴趣,机缘巧合公司做一个手游的项目,我就开始游戏服务器的折腾之旅. 游戏的构架是 ...

随机推荐

  1. 《JavaScript 代码优化指南》

      ~~教你向老鸟一样敲代码~~. 1. 将脚本放在页面的底部 ... <script src="./jquery.min.js"></script> &l ...

  2. 继续上篇抢QQ口令红包,抢那招抢不了的红包技巧

    - - - - - - - - - - -- - - --长按红包,出现回复,点击回复,那回复里有个表情,直接输入那个表情回复就可以抢了 - - - - - - - - --------------- ...

  3. HttpClient调用webApi时注意的小问题

    HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...

  4. 安装Oracle时出现环境变量Path的值大于1023的解决办法

    出现的情况我就不说了,直接重点: 计算机->属性->高级系统设置->高级->环境变量 1)在"系统变量"编辑Path,全选将其中的路径全部复制出来放到文本文 ...

  5. jQuery 中bind(),live(),delegate(),on() 区别(转)

    当我们试图绑定一些事件到DOM元素上的时候,我相信上面这4个方法是最常用的.而它们之间到底有什么不同呢?在什么场合下用什么方法是最有效的呢? 准备知识: 当我们在开始的时候,有些知识是必须具备的: D ...

  6. 深入浅出node(2) 模块机制

    这部分主要总结深入浅出Node.js的第二章 一)CommonJs 1.1CommonJs模块定义 二)Node的模块实现 2.1模块分类 2.2 路径分析和文件定位 2.2.1 路径分析 2.2.2 ...

  7. canvas贝塞尔曲线

    贝塞尔曲线 Bézier curve(贝塞尔曲线)是应用于二维图形应用程序的数学曲线. 曲线定义:起始点.终止点.控制点.通过调整控制点,贝塞尔曲线的形状会发生变化. 1962年,法国数学家Pierr ...

  8. AgilePoint实例属性修改

    流程实例中的参数存放在WF_CUSTOM_ATTRS表的WF_CUSTOM_ATTRS字段,为ntext类型,里面存放的是XML,不能直接修改   update [APData].[dbo].[WF_ ...

  9. Linux Distribution / ROM

    Linux发行版 http://unix.stackexchange.com/questions/87011/how-to-easily-build-your-own-linux-distro 这个文 ...

  10. 利用私有的API获得手机上所安装的所有应用信息(包括版本,名称,bundleID,类型)

    MobileCoreService这个系统的库,里面有个私有的类LSApplicationWorkspace ,利用运行时可以获得私有类里面的方法,- (id)allInstalledApplicat ...