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

  1. public class HttpServer {
  2. public void bind(int port) throws Exception {
  3. EventLoopGroup bossGroup = new NioEventLoopGroup();
  4. EventLoopGroup workerGroup = new NioEventLoopGroup();
  5. try {
  6. ServerBootstrap b = new ServerBootstrap();
  7. b.group(bossGroup, workerGroup)
  8. .channel(NioServerSocketChannel.class)
  9. .option(ChannelOption.SO_BACKLOG, 1024)
  10. .childHandler(new HttpChannelInitService()).option(ChannelOption.SO_BACKLOG, 128)
  11. .childOption(ChannelOption.SO_KEEPALIVE, true);
  12.  
  13. ChannelFuture f = b.bind(port).sync();
  14. f.channel().closeFuture().sync();
  15. } finally {
  16. bossGroup.shutdownGracefully();
  17. workerGroup.shutdownGracefully();
  18. }
  19. }
  20.  
  21. public static void main(String[] args) throws Exception {
  22. int port = 8080;
  23. if (args != null && args.length > 0) {
  24. try {
  25. port = Integer.valueOf(args[0]);
  26. } catch (NumberFormatException e) {
  27.  
  28. }
  29. }
  30. new HttpServer().bind(port);
  31. }
  32. }

2.HttpChannelInitService,通道初始化类

  1. public class HttpChannelInitService extends ChannelInitializer<SocketChannel>{
  2. @Override
  3. protected void initChannel(SocketChannel sc)
  4. throws Exception {
  5. sc.pipeline().addLast(new HttpResponseEncoder());
  6.  
  7. sc.pipeline().addLast(new HttpRequestDecoder());
  8.  
  9. sc.pipeline().addLast(new HttpChannelHandler());
  10. }
  11.  
  12. }

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

  1. public class HttpChannelHandler extends ChannelInboundHandlerAdapter {
  2.  
  3. private HttpRequest request = null;
  4. private FullHttpResponse response = null;
  5.  
  6. @Override
  7. public void channelRead(ChannelHandlerContext ctx, Object msg)
  8. throws Exception {
  9. if (msg instanceof HttpRequest) {
  10. request = (HttpRequest) msg;
  11. String uri = request.getUri();
  12. String res = "";
  13. try {
  14. res = ReadUtils.readFile(uri.substring(1));
  15. response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
  16. setJsessionId(isHasJsessionId());
  17. setHeaders(response);
  18. } catch (Exception e) {//处理出错,返回错误信息
  19. res = "<html><body>Server Error</body></html>";
  20. response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
  21. setHeaders(response);
  22.  
  23. }
  24. if(response!=null)
  25. ctx.write(response);
  26. }
  27. if (msg instanceof HttpContent) {
  28. HttpContent content = (HttpContent) msg;
  29. ByteBuf buf = content.content();
  30. System.out.println(buf.toString(CharsetUtil.UTF_8));
  31. buf.release();
  32. }
  33. }
  34. /**
  35. * 设置HTTP返回头信息
  36. */
  37. private void setHeaders(FullHttpResponse response) {
  38. response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
  39. response.headers().set(HttpHeaders.Names.CONTENT_LANGUAGE, response.content().readableBytes());
  40. if (HttpHeaders.isKeepAlive(request)) {
  41. response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
  42. }
  43. }
  44. /**
  45. * 设置JSESSIONID
  46. */
  47. private void setJsessionId(boolean isHasJsessionId) {
  48. if(!isHasJsessionId){
  49. CookieEncoder encoder = new CookieEncoder(true);
  50. encoder.addCookie(HttpSession.SESSIONID, HttpSessionManager.getSessionId());
  51. String encodedCookie = encoder.encode();
  52. response.headers().set(HttpHeaders.Names.SET_COOKIE, encodedCookie);
  53. }
  54. }
  55.  
  56. /**
  57. * 从cookie中获取JSESSIONID信息
  58. * 判断服务器是否有客户端的JSESSIONID
  59. * @author yangsong
  60. * @date 2015年3月26日 下午2:08:07
  61. */
  62. private boolean isHasJsessionId() {
  63. try {
  64. String cookieStr = request.headers().get("Cookie");
  65. Set<Cookie> cookies = CookieDecoder.decode(cookieStr);
  66. Iterator<Cookie> it = cookies.iterator();
  67.  
  68. while(it.hasNext()){
  69. Cookie cookie = it.next();
  70. if(cookie.getName().equals(HttpSession.SESSIONID)){
  71. if(HttpSessionManager.isHasJsessionId(cookie.getValue())){
  72. return true;
  73. }
  74. System.out.println("JSESSIONID:"+cookie.getValue());
  75.  
  76. }
  77. }
  78. } catch (Exception e1) {
  79. e1.printStackTrace();
  80. }
  81. return false;
  82. }
  83.  
  84. @Override
  85. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  86. System.out.println("server channelReadComplete..");
  87. ctx.flush();//刷新后才将数据发出到SocketChannel
  88. }
  89. @Override
  90. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  91. throws Exception {
  92. System.out.println("server exceptionCaught..");
  93. ctx.close();
  94. }
  95. }

5.HttpSessionManager,Session管理类

  1. /**
  2. * HttpSession管理器
  3. */
  4. public class HttpSessionManager {
  5.  
  6. private static final HashMap<String,HttpSession> sessionMap = new HashMap<String, HttpSession>();
  7.  
  8. /**
  9. * 创建一个session并返回sessionId
  10. */
  11. public static String getSessionId(){
  12. synchronized (sessionMap) {
  13. HttpSession httpSession = new HttpSession();
  14. sessionMap.put(httpSession.getSessionID(), httpSession);
  15. return httpSession.getSessionID();
  16. }
  17. }
  18. /**
  19. * 判断服务器是否包含该客户端的session信息
  20. */
  21. public static boolean isHasJsessionId(String sessiondId){
  22. synchronized (sessionMap) {
  23. return sessionMap.containsKey(sessiondId);
  24. }
  25. }
  26.  
  27. }

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. gitHub静态页面托管

    github已经是众所周知的程序员同性交友网站了,我就不多说了,(+_+)? 下面讲一讲如何在不用自己购买空间域名备案的情况下,通过github来托管自己的一些小demo或者项目 让其能够通过gith ...

  2. 目标跟踪之粒子滤波---Opencv实现粒子滤波算法

    目标跟踪学习笔记_2(particle filter初探1) 目标跟踪学习笔记_3(particle filter初探2) 前面2篇博客已经提到当粒子数增加时会内存报错,后面又仔细查了下程序,是代码方 ...

  3. testVC.modalPresentationStyle = UIModalPresentationFormSheet; 更改 VC大小

    本文转载至 http://www.cocoachina.com/bbs/simple/?t31199.html TestViewController *testVC = [[TestViewContr ...

  4. IE浏览器的判断

    function compatibleIE8(){ var browser = navigator.appName; var b_version = navigator.appVersion; if( ...

  5. zookeeper_action

    连接串 从节点列表本地缓存主节点对未分配的任务,随机分配给从节点(不合理??)从节点保存一个本地待执行任务列表单独的线程对节点已分配任务进行循环 进程p为了获锁——>创建节点znode_/loc ...

  6. CUDA: 流

    1. 页锁定主机内存 c库函数malloc()分配标准的,可分页(Pagable)的内存,cudaHostAlloc()分配页锁定的主机内存.页锁定内存也称为固定内存(Pinned Memory)或者 ...

  7. LeetCode:删除链表中的节点【203】

    LeetCode:删除链表中的节点[203] 题目描述 删除链表中等于给定值 val 的所有节点. 示例: 输入: 1->2->6->3->4->5->6, val ...

  8. BFC和haslayout(IE6-7)(待总结。。。)

    支持BFC的浏览器(IE8+,firefox,chrome,safari) Block Formatting Context(块格式化上下文)是W3C CSS2.1规范中的一个慨念,在CSS3中被修改 ...

  9. C# HttpRequest

    using System; using System.Collections; using System.Collections.Generic; using System.IO; using Sys ...

  10. Oracle 数据库SQL

    原作者:http://blog.csdn.net/jihuanliang/article/details/7205968 总体说说可能出现的原因: 情况场景: 表A中有个字段是外键,关联了表B中的某字 ...