1.HttpServer,Http服务启动类,用于初始化各种线程和通道

public class HttpServer {
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new HttpChannelInitService()).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) { }
}
new HttpServer().bind(port);
}
}

2.HttpChannelInitService,通道初始化类

public class HttpChannelInitService extends  ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel sc)
throws Exception {
sc.pipeline().addLast(new HttpResponseEncoder()); sc.pipeline().addLast(new HttpRequestDecoder()); sc.pipeline().addLast(new HttpChannelHandler());
} }

3.HttpChannelHandler,处理请求的HTTP信息

public class HttpChannelHandler extends ChannelInboundHandlerAdapter {

     private HttpRequest request = null;
private FullHttpResponse response = null; @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
if (msg instanceof HttpRequest) {
request = (HttpRequest) msg;
String uri = request.getUri();
String res = "";
try {
res = ReadUtils.readFile(uri.substring(1));
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
setJsessionId(isHasJsessionId());
setHeaders(response);
} catch (Exception e) {//处理出错,返回错误信息
res = "<html><body>Server Error</body></html>";
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
setHeaders(response); }
if(response!=null)
ctx.write(response);
}
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
ByteBuf buf = content.content();
System.out.println(buf.toString(CharsetUtil.UTF_8));
buf.release();
}
}
/**
* 设置HTTP返回头信息
*/
private void setHeaders(FullHttpResponse response) {
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.headers().set(HttpHeaders.Names.CONTENT_LANGUAGE, response.content().readableBytes());
if (HttpHeaders.isKeepAlive(request)) {
response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
}
}
/**
* 设置JSESSIONID
*/
private void setJsessionId(boolean isHasJsessionId) {
if(!isHasJsessionId){
CookieEncoder encoder = new CookieEncoder(true);
encoder.addCookie(HttpSession.SESSIONID, HttpSessionManager.getSessionId());
String encodedCookie = encoder.encode();
response.headers().set(HttpHeaders.Names.SET_COOKIE, encodedCookie);
}
} /**
* 从cookie中获取JSESSIONID信息
* 判断服务器是否有客户端的JSESSIONID
* @author yangsong
* @date 2015年3月26日 下午2:08:07
*/
private boolean isHasJsessionId() {
try {
String cookieStr = request.headers().get("Cookie");
Set<Cookie> cookies = CookieDecoder.decode(cookieStr);
Iterator<Cookie> it = cookies.iterator(); while(it.hasNext()){
Cookie cookie = it.next();
if(cookie.getName().equals(HttpSession.SESSIONID)){
if(HttpSessionManager.isHasJsessionId(cookie.getValue())){
return true;
}
System.out.println("JSESSIONID:"+cookie.getValue()); }
}
} catch (Exception e1) {
e1.printStackTrace();
}
return false;
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("server channelReadComplete..");
ctx.flush();//刷新后才将数据发出到SocketChannel
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
System.out.println("server exceptionCaught..");
ctx.close();
}
}

5.HttpSessionManager,Session管理类

/**
* HttpSession管理器
*/
public class HttpSessionManager { private static final HashMap<String,HttpSession> sessionMap = new HashMap<String, HttpSession>(); /**
* 创建一个session并返回sessionId
*/
public static String getSessionId(){
synchronized (sessionMap) {
HttpSession httpSession = new HttpSession();
sessionMap.put(httpSession.getSessionID(), httpSession);
return httpSession.getSessionID();
}
}
/**
* 判断服务器是否包含该客户端的session信息
*/
public static boolean isHasJsessionId(String sessiondId){
synchronized (sessionMap) {
return sessionMap.containsKey(sessiondId);
}
} }

6.页面信息与cookie

使用Netty实现的一个简单HTTP服务器的更多相关文章

  1. 用nodejs搭建一个简单的服务器

    使用nodejs搭建一个简单的服务器 nodejs优点:性能高(读写文件) 数据操作能力强 官网:www.nodejs.org 验证是否安装成功:cmd命令行中输入node -v 如果显示版本号表示安 ...

  2. 初学Node(六)搭建一个简单的服务器

    搭建一个简单的服务器 通过下面的代码可以搭建一个简单的服务器: var http = require("http"); http.createServer(function(req ...

  3. 轻松创建nodejs服务器(1):一个简单nodejs服务器例子

    这篇文章主要介绍了一个简单nodejs服务器例子,本文实现了一个简单的hello world例子,并展示如何运行这个服务器,需要的朋友可以参考下   我们先来实现一个简单的例子,hello world ...

  4. Node学习(二) --使用http和fs模块实现一个简单的服务器

    1.创建一个www目录,存储静态文件1.html.1.jpg. * html文件内容如下: 12345678910111213 <html lang="en">< ...

  5. Express 的基本使用(创建一个简单的服务器)

    Express 的基本使用(创建一个简单的服务器) const express = require('express') // 创建服务器应用程序 // 相当于 http.creatServer co ...

  6. Netty练手项目-简单Http服务器

    简单的设计思路就是,启动一个可以截断并处理Http请求的服务器代码.使用netty提供的boss线程与worker线程的模型,并使用netty的http解码器.自行编写了http url处理的部分.在 ...

  7. 理解与模拟一个简单web服务器

    先简单说下几个概念,根据自己的理解,不正确请见谅. web服务器 首先要知道什么是web服务器,简单说web服务器就是可以使用HTTP传输协议与客户端进行通信的服务器.最初的web服务器只能用来处理静 ...

  8. Linux:写一个简单的服务器

    开始了新篇章:Linux网络编程. 基础知识: 套接字概念 Socket本身有"插座"的意思,在Linux环境下,用于表示进程间网络通信的特殊文件类型.本质为内核借助缓冲区形成的伪 ...

  9. Windows 上静态编译 Libevent 2.0.10 并实现一个简单 HTTP 服务器(无数截图)

    [文章作者:张宴 本文版本:v1.0 最后修改:2011.03.30 转载请注明原文链接:http://blog.s135.com/libevent_windows/] 本文介绍了如何在 Window ...

随机推荐

  1. python 基础 5.4 类的私有属性和私有方法

    一. 类的私有变量和私有方法 1>   在python 中可以通过在属性变量名前,加上双下划线定义属性为私有属性   2>特殊变量命名 a. _xx 以单下划线开头的表示的是protect ...

  2. lombok插件安装

    eclipse安装lombok插件 lombok注解介绍 记得最后,加入的配置文件中的jar包,最好写成相对路径,这样.eclipse移动位置后,不会报错.

  3. Unix环境高级编程—进程控制(二)

    一.函数wait和waitpid 今天我们继续通过昨天那个死爹死儿子的故事来讲(便于记忆),现在看看wait和waitpid函数. #include<sys/wait.h> pid_t w ...

  4. EasyRTMP+EasyDSS实现一套完整的紧急视频回传直播与存储回放方案

    需求来源 紧急视频回传云端:即拍即传.云端存储.紧急录像.云拍云录!这些需求现在可能对于我们来说比较远,大部分也是在行业中才会用到,但相信在不就的将来肯定会落地到每个人的手中,因为这是一个自我保护.自 ...

  5. Java基础之Comparable接口, Collections类,Iterator接口,泛型(Generic)

    一.Comparable接口, Collections类 List的常用算法: sort(List); 排序,如果需要对自定义的类进行排序, 那就必须要让其实现Comparable接口, 实现比较两个 ...

  6. [数据挖掘课程笔记]无监督学习——聚类(clustering)

    什么是聚类(clustering) 个人理解:聚类就是将大量无标签的记录,根据它们的特点把它们分成簇,最后结果应当是相同簇之间相似性要尽可能大,不同簇之间相似性要尽可能小. 聚类方法的分类如下图所示: ...

  7. ruby 精选网站

    ruby 基础   http://www.yiibai.com/ruby/2013/0820174.html     http://www.rubydoc.info/github       http ...

  8. BZOJ 2819 Nim 树链剖分+树状数组

    这题真没什么意思. 不过就是将普通的求Min,Max,求和等东西换成Xor,偏偏Xor还有很多性质. 算是刷道水题吧. #include<iostream> #include<cst ...

  9. Android WiFi系统【转】

    本文转载自:http://blog.csdn.net/gabbzang/article/details/10584587 一.wpa_supplicant是什么? wpa_supplicant本是开源 ...

  10. ASP.NET MVC3中的路由系统

    MVC中,用户访问的地址并不映射到服务器中对应的文件,而是映射到对应Control里对应的ActionMethod,由ActionMethod来决定返回用户什么样的信息.而把用户访问的地址对应到对应的 ...