1.服务器端

  1. import io.netty.bootstrap.ServerBootstrap;
  2. import io.netty.buffer.PooledByteBufAllocator;
  3. import io.netty.channel.Channel;
  4. import io.netty.channel.ChannelOption;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.handler.ssl.SslContext;
  7. import io.netty.handler.ssl.SslContextBuilder;
  8. import io.netty.handler.ssl.util.SelfSignedCertificate;
  9. import io.netty.channel.epoll.EpollEventLoopGroup;
  10. import io.netty.channel.epoll.EpollServerSocketChannel;
  11. /**
  12. * An HTTP server that sends back the content of the received HTTP request
  13. * in a pretty plaintext form.
  14. */
  15. public final class HttpHelloWorldServer {
  16.  
  17. static final boolean SSL = System.getProperty("ssl") != null;
  18. static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
  19.  
  20. public static void main(String[] args) throws Exception {
  21. // Configure SSL.
  22. final SslContext sslCtx;
  23. if (SSL) {
  24. SelfSignedCertificate ssc = new SelfSignedCertificate();
  25. sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
  26. } else {
  27. sslCtx = null;
  28. }
  29.  
  30. // Configure the server.
  31. EventLoopGroup bossGroup = new EpollEventLoopGroup(1);
  32. EventLoopGroup workerGroup = new EpollEventLoopGroup();
  33.  
  34. try {
  35. ServerBootstrap b = new ServerBootstrap();
  36. b.channel(EpollServerSocketChannel.class);
  37. b.option(ChannelOption.SO_BACKLOG, 1024);
  38. b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
  39. b.group(bossGroup, workerGroup)
  40. // .handler(new LoggingHandler(LogLevel.INFO))
  41. .childHandler(new HttpHelloWorldServerInitializer(sslCtx));
  42.  
  43. Channel ch = b.bind(PORT).sync().channel();
  44. /* System.err.println("Open your web browser and navigate to " +
  45. (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');*/
  46. ch.closeFuture().sync();
  47. } finally {
  48. bossGroup.shutdownGracefully();
  49. workerGroup.shutdownGracefully();
  50. }
  51. }
  52. }

其中

  1. HttpHelloWorldServerInitializer代码如下:
  1. import io.netty.channel.ChannelInitializer;
  2. import io.netty.channel.ChannelPipeline;
  3. import io.netty.channel.socket.SocketChannel;
  4. import io.netty.handler.codec.http.HttpServerCodec;
  5. import io.netty.handler.ssl.SslContext;
  6.  
  7. public class HttpHelloWorldServerInitializer extends ChannelInitializer<SocketChannel> {
  8.  
  9. private final SslContext sslCtx;
  10.  
  11. public HttpHelloWorldServerInitializer(SslContext sslCtx) {
  12. this.sslCtx = sslCtx;
  13. }
  14.  
  15. @Override
  16. public void initChannel(SocketChannel ch) {
  17. ChannelPipeline p = ch.pipeline();
  18. if (sslCtx != null) {
  19. p.addLast(sslCtx.newHandler(ch.alloc()));
  20. }
  21. p.addLast(new HttpServerCodec());
  22. p.addLast(new HttpHelloWorldServerHandler());
  23. }
  24. }

其中,

  1. HttpHelloWorldServerHandler 代码如下:
  1. import io.netty.buffer.Unpooled;
  2. import io.netty.channel.ChannelFutureListener;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.ChannelInboundHandlerAdapter;
  5. import io.netty.handler.codec.http.DefaultFullHttpResponse;
  6. import io.netty.handler.codec.http.FullHttpResponse;
  7. import io.netty.handler.codec.http.HttpUtil;
  8. import io.netty.handler.codec.http.HttpRequest;
  9. import io.netty.util.AsciiString;
  10. import static io.netty.handler.codec.http.HttpResponseStatus.*;
  11. import static io.netty.handler.codec.http.HttpVersion.*;
  12.  
  13. public class HttpHelloWorldServerHandler extends ChannelInboundHandlerAdapter {
  14. private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
  15.  
  16. private static final AsciiString CONTENT_TYPE = new AsciiString("Content-Type");
  17. private static final AsciiString CONTENT_LENGTH = new AsciiString("Content-Length");
  18. private static final AsciiString CONNECTION = new AsciiString("Connection");
  19. private static final AsciiString KEEP_ALIVE = new AsciiString("keep-alive");
  20.  
  21. @Override
  22. public void channelReadComplete(ChannelHandlerContext ctx) {
  23. ctx.flush();
  24. }
  25.  
  26. @Override
  27. public void channelRead(ChannelHandlerContext ctx, Object msg) {
  28. if (msg instanceof HttpRequest) {
  29. HttpRequest req = (HttpRequest) msg;
  30.  
  31. if (HttpUtil.is100ContinueExpected(req)) {
  32. ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
  33. }
  34. boolean keepAlive = HttpUtil.isKeepAlive(req);
  35. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
  36. response.headers().set(CONTENT_TYPE, "text/plain");
  37. response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
  38.  
  39. if (!keepAlive) {
  40. ctx.write(response).addListener(ChannelFutureListener.CLOSE);
  41. } else {
  42. response.headers().set(CONNECTION, KEEP_ALIVE);
  43. ctx.write(response);
  44. }
  45. }
  46. }
  47.  
  48. @Override
  49. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  50. cause.printStackTrace();
  51. ctx.close();
  52. }
  53. }

netty epoll调用示例的更多相关文章

  1. 股票数据调用示例代码php

    <!--?php // +---------------------------------------------------------------------- // | JuhePHP ...

  2. WebService核心文件【server-config.wsdd】详解及调用示例

    WebService核心文件[server-config.wsdd]详解及调用示例 作者:Vashon 一.准备工作 导入需要的jar包: 二.配置web.xml 在web工程的web.xml中添加如 ...

  3. Windows API 调用示例

    Ø  简介 本文主要记录 Windows API 的调用示例,因为这项技术并不常用,属于 C# 中比较孤僻或接触底层的技术,并不常用.但是有时候也可以借助他完成一些 C# 本身不能完成的功能,例如:通 ...

  4. C#中异步调用示例与详解

    using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...

  5. HTML 百度地图API调用示例源码

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  6. C#全能数据库操作类及调用示例

    C#全能数据库操作类及调用示例 using System; using System.Data; using System.Data.Common; using System.Configuratio ...

  7. 利用JavaScriptSOAPClient直接调用webService --完整的前后台配置与调用示例

    JavaScriptSoapClient下载地址:https://archive.codeplex.com/?p=javascriptsoapclient JavaScriptSoapClient的D ...

  8. Web Api跨域访问配置及调用示例

    1.Web Api跨域访问配置. 在Web.config中的system.webServer内添加以下代码: <httpProtocol> <customHeaders> &l ...

  9. 搭建coreseek(sphinx+mmseg3)详细安装配置+php之sphinx扩展安装+php调用示例(转)

    一个文档包含了安装.增量备份.扩展.api调用示例,省去了查找大量文章的时间. 搭建coreseek(sphinx+mmseg3)安装 [第一步] 先安装mmseg3 cd /var/install ...

随机推荐

  1. ASP.Net简单的交互案例

    控制器 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Syste ...

  2. CSS3的属性选择器

    CSS3中新增了许多选择器,今天零度给大家说说CSS3的属性选择器. 与CSS2相比,CSS3新增了3种属性选择器:[attr^=value].[attr$=value].[attr*=value]: ...

  3. Linux下几种另类创建文件之方法

    以前我们用编辑器例如vi来新建文件,下面介绍几种另类生成文件的方法,多用在备份和测试上. 创建文件的方法: 1.echo 命令    #echo "set bell"  >& ...

  4. 网上看到的一些IT资源

    A.网站模板+logo+服务器主机+发票生成 HTML5 UP:响应式的HTML5和CSS3网站模板. Bootswatch:免费的Bootstrap主题. Templated:收集了845个免费的C ...

  5. MATLAB 软件学习

    what  列出当前目录或指定目录下的M\MAT 和 MAX 文件 …   在语句行尾端表示该行未完 !  调用操作系统的命令 isvarname  判断变量名是否有效 声明全局变量   变量名前加 ...

  6. LuoguP3254 圆桌问题(最大流)

    题目描述 假设有来自m 个不同单位的代表参加一次国际会议.每个单位的代表数分别为ri (i =1,2,……,m). 会议餐厅共有n 张餐桌,每张餐桌可容纳ci (i =1,2,……,n)个代表就餐. ...

  7. VMwarep挂载镜像及配置本地Yum源

    1.挂载镜像: *. 通过mount命令         linux mount挂载设备(u盘,光盘,iso等 )使用说明 *.  通过VMware的控制页面手工挂载 1.1    打开Vmware软 ...

  8. Myeclipse学习总结(2)——MyEclipse快捷键大全

    1.ctrl+shift+R 打开资源 此组快捷键可以打开工程中任意一个文件,而本人只需按文件名或者mask名的字母顺序输入就会出现对应的文件或者在内容中某个关键字再按快捷键也可以的,例如:Custo ...

  9. 数字签名算法--3.ECDSA

    package Imooc; import java.security.KeyFactory; import java.security.KeyPair; import java.security.K ...

  10. [Angular & Unit Testing] TestBed.get vs Injector

    Both what "TestBed.get" & "injector" trying to do is get service for the tes ...