简单的 http 服务器
简单的基于socket和NIO的 http server示例:
项目路径:https://github.com/windwant/windwant-demo/tree/master/httpserver-demo
1. Request:
package org.windwant.httpserver; import java.io.IOException;
import java.io.InputStream; /**
* Created by windwant on 2016/6/12.
*/
public class Request { private InputStream in; public String getUri() {
return uri;
} private String uri; public Request(){} public Request(InputStream in){
this.in = in;
} public void read(){
StringBuffer sb = new StringBuffer();
int i = 0;
byte[] b = new byte[2048];
try {
i = in.read(b);
for (int j = 0; j < i; j++) {
sb.append((char)b[j]);
}
takeUri(sb);
} catch (IOException e) {
e.printStackTrace();
}
} public void takeUri(StringBuffer sb){
int i = sb.indexOf(" ");
if(i > 0){
int j = sb.indexOf(" ", i + 1);
if(j > 0){
uri = sb.substring(i + 1, j).toString();
System.out.println("http request uri: " + uri);
if(!(uri.endsWith("/index.html") || uri.endsWith("/test.jpg"))){
uri = "/404.html";
System.out.println("http request uri rewrite: " + uri);
}
}
}
} }
2. Response:
package org.windwant.httpserver; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel; /**
* Created by windwant on 2016/6/12.
*/
public class Response {
private static final int BUFFER_SIZE = 1024; public void setRequest(Request request) {
this.request = request;
} Request request; OutputStream out; SocketChannel osc; public Response(OutputStream out){
this.out = out;
} public Response(SocketChannel osc){
this.osc = osc;
} public void response(){
byte[] b = new byte[BUFFER_SIZE];
File file = new File(HttpServer.WEB_ROOT, request.getUri());
try {
StringBuilder sb = new StringBuilder();
if(file.exists()){
FileInputStream fi = new FileInputStream(file);
int ch = 0;
while ((ch = fi.read(b, 0, BUFFER_SIZE)) > 0){
out.write(b, 0, ch);
}
out.flush();
}else{
sb.append("HTTP/1.1 404 File Not Found \r\n");
sb.append("Content-Type: text/html\r\n");
sb.append("Content-Length: 24\r\n" );
sb.append("\r\n" );
sb.append("<h1>File Not Found!</h1>");
out.write(sb.toString().getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public void responseNIO(){
byte[] b = new byte[BUFFER_SIZE];
File file = new File(HttpServer.WEB_ROOT, request.getUri());
try {
StringBuilder sb = new StringBuilder();
if(file != null && file.exists()){
FileInputStream fi = new FileInputStream(file);
while (fi.read(b) > 0){
osc.write(ByteBuffer.wrap(b));
b = new byte[BUFFER_SIZE];
}
}else{
sb.append("HTTP/1.1 404 File Not Found \r\n");
sb.append("Content-Type: text/html\r\n");
sb.append("Content-Length: 24\r\n" );
sb.append("\r\n" );
sb.append("<h1>File Not Found!</h1>");
osc.write(ByteBuffer.wrap(sb.toString().getBytes()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }
3. HttpServer:
package org.windwant.httpserver; 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 windwant on 2016/6/12.
*/
public class HttpServer {
public static final String WEB_ROOT = System.getProperty("user.dir") + "\\src\\test\\resources\\webroot";
public static final int SERVER_PORT = 8888;
public static final String SERVER_IP = "127.0.0.1"; public static void main(String[] args) {
HttpServer httpServer = new HttpServer();
httpServer.await();
} public void await(){
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(SERVER_PORT, 1, InetAddress.getByName(SERVER_IP));
while (true){
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
Request request = new Request(in);
request.read(); Response response = new Response(out);
response.setRequest(request);
response.response();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. HttpNIOServer:
package org.windwant.httpserver; import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* Created by windwant on 2016/6/13.
*/
public class HttpNIOServer { private ServerSocketChannel serverSocketChannel; private ServerSocket serverSocket; private Selector selector; Request request; private ExecutorService es; private static final Integer SERVER_PORT = 8888; public void setShutdown(boolean shutdown) {
this.shutdown = shutdown;
} private boolean shutdown = false; public static void main(String[] args) {
HttpNIOServer server = new HttpNIOServer();
server.start();
System.exit(0);
} HttpNIOServer(){
try {
es = Executors.newFixedThreadPool(5);
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocket = serverSocketChannel.socket();
serverSocket.bind(new InetSocketAddress(SERVER_PORT)); selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("server init...");
} catch (IOException e) {
e.printStackTrace();
}
} public void start(){
try {
while (!shutdown){
selector.select();
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeySet.iterator();
while (it.hasNext()){
SelectionKey selectionKey = it.next();
it.remove();
handleRequest(selectionKey);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} public void handleRequest(SelectionKey selectionKey){
ServerSocketChannel ssc = null;
SocketChannel ss = null;
try {
if(selectionKey.isAcceptable()){
ssc = (ServerSocketChannel) selectionKey.channel();
ss = ssc.accept(); ss.configureBlocking(false);
ss.register(selector, SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
ss = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
StringBuffer sb = new StringBuffer();
while (ss.read(byteBuffer) > 0){
byteBuffer.flip();
int lgn = byteBuffer.limit();
for (int i = 0; i < lgn; i++) {
sb.append((char)byteBuffer.get(i));
}
byteBuffer.clear();
}
if(sb.length() > 0) {
request = new Request();
request.takeUri(sb);
ss.register(selector, SelectionKey.OP_WRITE);
}
}else if(selectionKey.isWritable()){
ss = (SocketChannel) selectionKey.channel();
ByteBuffer rb = ByteBuffer.allocate(2048);
Response response = new Response(ss);
response.setRequest(request);
response.responseNIO();
ss.register(selector, SelectionKey.OP_READ);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
简单的 http 服务器的更多相关文章
- 使用 Nodejs 搭建简单的Web服务器
使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...
- 一个简单的 Web 服务器 [未完成]
最近学习C++,linux和网络编程,想做个小(mini)项目. 就去搜索引擎, 开源中国, Sourceforge上找http server的项目. 好吧,也去了知乎. 知乎上程序员氛围好, ...
- 20145216 20145330 《信息安全系统设计基础》 实验五 简单嵌入式WEB 服务器实验
20145216 20145330 <信息安全系统设计基础> 实验五 简单嵌入式WEB 服务器实验 实验报告封面 实验步骤 1.阅读理解源码 进入/arm2410cl/exp/basic/ ...
- 自己动手模拟开发一个简单的Web服务器
开篇:每当我们将开发好的ASP.NET网站部署到IIS服务器中,在浏览器正常浏览页面时,可曾想过Web服务器是怎么工作的,其原理是什么?“纸上得来终觉浅,绝知此事要躬行”,于是我们自己模拟一个简单的W ...
- 深入剖析tomcat之一个简单的web服务器
这个简单的web服务器包含三个类 HttpServer Request Response 在应用程序的入口点,也就是静态main函数中,创建一个HttpServer实例,然后调用其await()方法. ...
- 20145208《信息安全系统设计基础》实验五 简单嵌入式WEB 服务器实验
20145208<信息安全系统设计基础>实验五 简单嵌入式WEB 服务器实验 20145208<信息安全系统设计基础>实验五 简单嵌入式WEB 服务器实验
- 用Python建立最简单的web服务器
利用Python自带的包可以建立简单的web服务器.在DOS里cd到准备做服务器根目录的路径下,输入命令: python -m Web服务器模块 [端口号,默认8000] 例如: python -m ...
- 计算机网络(13)-----java nio手动实现简单的http服务器
java nio手动实现简单的http服务器 需求分析 最近在学习HTTP协议,还是希望动手去做一做,所以就自己实现了一个http服务器,主要功能是将http请求封装httpRequest,通过解析 ...
- 20145210 20145226 《信息安全系统设计基础》实验五 简单嵌入式WEB服务器实验
20145210 20145226 <信息安全系统设计基础>实验五 简单嵌入式WEB服务器实验 结对伙伴:20145226 夏艺华 实验报告封面 实验目的与要求 · 掌握在ARM开发板实现 ...
- 20145221 《信息安全系统设计基础》实验五 简单嵌入式WEB服务器实验
20145221 <信息安全系统设计基础>实验五 简单嵌入式WEB服务器实验 实验报告 队友博客:20145326蔡馨熠 实验博客:<信息安全系统设计基础>实验五 简单嵌入式W ...
随机推荐
- API 开发实践
整个2015年,如果要给自己打上一个标签的话,那应该就是 API. 在各个不同的系统中定制各种 API 框架. 在做商城对接各种电商 ERP 的 API 开发中,我采用的是兼容SHOPEX 的 API ...
- MUI(4)
今天感觉无聊,想听一首音乐.没有添加其他页面,只是在index_list.html页面进行代码添加而已. <!doctype html> <html> <head> ...
- 配置云服务器 FTP 服务
自己配置的环境: OS: 阿里云 CentOS 6.5 >>Begin: 1. 登录到阿里云服务器(如何登录阿里云服务器), 在root权限下, 通过如下命令安装 vsftp [root@ ...
- GJM : 【C# 高性能服务器】完成端口、心跳的高性能Socket服务器 [转载]
感谢您的阅读.喜欢的.有用的就请大哥大嫂们高抬贵手"推荐一下"吧!你的精神支持是博主强大的写作动力以及转载收藏动力.欢迎转载! 版权声明:本文原创发表于 [请点击连接前往] ,未经 ...
- wso2esb简介
WSO2 ESB是一个轻量级的易于使用的企业服务资源总线,基于Apache Software License v2.0. WSO2 ESB 允许系统管理员和SOA架构师轻松的配置消息路由, 虚拟化, ...
- Community Value再理解
其实之前写“从香港机房引入google/bitbucket路由”的时候,对community value的了解还并不深入,对Juniper default BGP export/import poli ...
- Ouibounce – 在用户离开你网站时显示模态弹窗
Ouibounce 是一个微小的库,用于实现在用户离开你的网站的时候显示一个模式窗口.这个库可以帮助你增加着陆页的转换率. Ouibounce 会在当鼠标光标移动到接近(或通过)视口(viewport ...
- Shepherd – 在应用程序中轻松实现引导功能
Shepherd 是一个指导用户使用应用程序的 JavaScript 库.它使用 Tether——另一个开源库,实现所有的步骤.Tether 确保你的步骤不会溢出屏幕或被剪裁.你可以很容易地指导用户使 ...
- 推荐15款最佳的响应式 Web 设计测试工具
响应式网页设计是根据设备的屏幕尺寸,平台和方向来开发的网页,是一种对最终用户的行为和环境作出反应的方法.响应式设计使用灵活的网格和布局,图像和智能使用 CSS 媒体查询的组合.当从它们在不同设备使用的 ...
- 如何使用递归遍历对象获得value值
一般要用到递归,就要判断对象是否和父类型是否一样 这里演示简单的对象递归,还有数组递归类似. var obj = { a:{w:1,y:2,x:3}, b:{s:4,j:5,x:6}, c:{car: ...