简单的 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 ...
随机推荐
- Using Recursive Common table expressions to represent Tree structures
http://www.postgresonline.com/journal/archives/131-Using-Recursive-Common-table-expressions-to-repre ...
- 数据查询语言DQL 与 内置函数(聚合函数)
数据查询语言DQL 从表中获取符合条件的数据 select select*from表的名字 查询表所有的数据.(select跟from必须一块用 成对出现的) * 表示所有字段,可以换成想要查询的 ...
- Scalaz(14)- Monad:函数组合-Kleisli to Reader
Monad Reader就是一种函数的组合.在scalaz里函数(function)本身就是Monad,自然也就是Functor和applicative.我们可以用Monadic方法进行函数组合: i ...
- 清除浮动类的css
.clearfix:after{ content:; visibility:hidden; display:block; clear:both;} .clearfix{ zoom:;}
- ENVI软件操作【数据显示操作——Overlay菜单操作】
一.注记层(Annotation) 注记层是ENVI的一个数据类型,它的后缀名是.ann.往往作为栅格数据层,矢量数据层.三维场景会绘图图表的附加数据叠加在上面,还可以作为镶嵌图像时候的裁剪线.注记数 ...
- HoverTree菜单0.1.3新增效果
HoverTree菜单0.1.3增加弹出菜单的动态效果,可以是动态下拉,也可以是动态淡入. 效果请看:http://keleyi.com/jq/hovertree/demo/demo.0.1.3.ht ...
- Asp.net Ibatis 增、删、改、查
好久都没用.net Ibatis配置了 今天给大家分享一下获取它的增.删.改.查. #region 节点类型表 public bool InsertNodeType(NodeType allRevie ...
- 完美卸载oracle11g步骤
完美卸载oracle11g步骤:1. 开始->设置->控制面板->管理工具->服务 停止所有Oracle服务.2. 开始->程序->Oracle - OraHome ...
- CloudStack安装
1.修改IP vi /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0 TYPE=Ethernet ONBOOT=yes NM_CONTROLL ...
- ArcGIS中国工具2.2正式发布
ArcGIS中国工具2.2新功能 1. 2.0全面支持ArcGIS10.3 2. 全面修改成插件,原来部分是独立运行的EXE 3. 可以制作倾斜的矩形图框 4. 修改宗地(地块)左上角为第一个点,填写 ...