netty epoll调用示例
1.服务器端
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.buffer.PooledByteBufAllocator;
- import io.netty.channel.Channel;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.handler.ssl.SslContext;
- import io.netty.handler.ssl.SslContextBuilder;
- import io.netty.handler.ssl.util.SelfSignedCertificate;
- import io.netty.channel.epoll.EpollEventLoopGroup;
- import io.netty.channel.epoll.EpollServerSocketChannel;
- /**
- * An HTTP server that sends back the content of the received HTTP request
- * in a pretty plaintext form.
- */
- public final class HttpHelloWorldServer {
- static final boolean SSL = System.getProperty("ssl") != null;
- static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
- public static void main(String[] args) throws Exception {
- // Configure SSL.
- final SslContext sslCtx;
- if (SSL) {
- SelfSignedCertificate ssc = new SelfSignedCertificate();
- sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
- } else {
- sslCtx = null;
- }
- // Configure the server.
- EventLoopGroup bossGroup = new EpollEventLoopGroup(1);
- EventLoopGroup workerGroup = new EpollEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.channel(EpollServerSocketChannel.class);
- b.option(ChannelOption.SO_BACKLOG, 1024);
- b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
- b.group(bossGroup, workerGroup)
- // .handler(new LoggingHandler(LogLevel.INFO))
- .childHandler(new HttpHelloWorldServerInitializer(sslCtx));
- Channel ch = b.bind(PORT).sync().channel();
- /* System.err.println("Open your web browser and navigate to " +
- (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');*/
- ch.closeFuture().sync();
- } finally {
- bossGroup.shutdownGracefully();
- workerGroup.shutdownGracefully();
- }
- }
- }
其中
- HttpHelloWorldServerInitializer代码如下:
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelPipeline;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.handler.codec.http.HttpServerCodec;
- import io.netty.handler.ssl.SslContext;
- public class HttpHelloWorldServerInitializer extends ChannelInitializer<SocketChannel> {
- private final SslContext sslCtx;
- public HttpHelloWorldServerInitializer(SslContext sslCtx) {
- this.sslCtx = sslCtx;
- }
- @Override
- public void initChannel(SocketChannel ch) {
- ChannelPipeline p = ch.pipeline();
- if (sslCtx != null) {
- p.addLast(sslCtx.newHandler(ch.alloc()));
- }
- p.addLast(new HttpServerCodec());
- p.addLast(new HttpHelloWorldServerHandler());
- }
- }
其中,
- HttpHelloWorldServerHandler 代码如下:
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelFutureListener;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.handler.codec.http.DefaultFullHttpResponse;
- import io.netty.handler.codec.http.FullHttpResponse;
- import io.netty.handler.codec.http.HttpUtil;
- import io.netty.handler.codec.http.HttpRequest;
- import io.netty.util.AsciiString;
- import static io.netty.handler.codec.http.HttpResponseStatus.*;
- import static io.netty.handler.codec.http.HttpVersion.*;
- public class HttpHelloWorldServerHandler extends ChannelInboundHandlerAdapter {
- private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
- private static final AsciiString CONTENT_TYPE = new AsciiString("Content-Type");
- private static final AsciiString CONTENT_LENGTH = new AsciiString("Content-Length");
- private static final AsciiString CONNECTION = new AsciiString("Connection");
- private static final AsciiString KEEP_ALIVE = new AsciiString("keep-alive");
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) {
- ctx.flush();
- }
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- if (msg instanceof HttpRequest) {
- HttpRequest req = (HttpRequest) msg;
- if (HttpUtil.is100ContinueExpected(req)) {
- ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
- }
- boolean keepAlive = HttpUtil.isKeepAlive(req);
- FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
- response.headers().set(CONTENT_TYPE, "text/plain");
- response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
- if (!keepAlive) {
- ctx.write(response).addListener(ChannelFutureListener.CLOSE);
- } else {
- response.headers().set(CONNECTION, KEEP_ALIVE);
- ctx.write(response);
- }
- }
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- cause.printStackTrace();
- ctx.close();
- }
- }
netty epoll调用示例的更多相关文章
- 股票数据调用示例代码php
<!--?php // +---------------------------------------------------------------------- // | JuhePHP ...
- WebService核心文件【server-config.wsdd】详解及调用示例
WebService核心文件[server-config.wsdd]详解及调用示例 作者:Vashon 一.准备工作 导入需要的jar包: 二.配置web.xml 在web工程的web.xml中添加如 ...
- Windows API 调用示例
Ø 简介 本文主要记录 Windows API 的调用示例,因为这项技术并不常用,属于 C# 中比较孤僻或接触底层的技术,并不常用.但是有时候也可以借助他完成一些 C# 本身不能完成的功能,例如:通 ...
- C#中异步调用示例与详解
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...
- HTML 百度地图API调用示例源码
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- C#全能数据库操作类及调用示例
C#全能数据库操作类及调用示例 using System; using System.Data; using System.Data.Common; using System.Configuratio ...
- 利用JavaScriptSOAPClient直接调用webService --完整的前后台配置与调用示例
JavaScriptSoapClient下载地址:https://archive.codeplex.com/?p=javascriptsoapclient JavaScriptSoapClient的D ...
- Web Api跨域访问配置及调用示例
1.Web Api跨域访问配置. 在Web.config中的system.webServer内添加以下代码: <httpProtocol> <customHeaders> &l ...
- 搭建coreseek(sphinx+mmseg3)详细安装配置+php之sphinx扩展安装+php调用示例(转)
一个文档包含了安装.增量备份.扩展.api调用示例,省去了查找大量文章的时间. 搭建coreseek(sphinx+mmseg3)安装 [第一步] 先安装mmseg3 cd /var/install ...
随机推荐
- ASP.Net简单的交互案例
控制器 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Syste ...
- CSS3的属性选择器
CSS3中新增了许多选择器,今天零度给大家说说CSS3的属性选择器. 与CSS2相比,CSS3新增了3种属性选择器:[attr^=value].[attr$=value].[attr*=value]: ...
- Linux下几种另类创建文件之方法
以前我们用编辑器例如vi来新建文件,下面介绍几种另类生成文件的方法,多用在备份和测试上. 创建文件的方法: 1.echo 命令 #echo "set bell" >& ...
- 网上看到的一些IT资源
A.网站模板+logo+服务器主机+发票生成 HTML5 UP:响应式的HTML5和CSS3网站模板. Bootswatch:免费的Bootstrap主题. Templated:收集了845个免费的C ...
- MATLAB 软件学习
what 列出当前目录或指定目录下的M\MAT 和 MAX 文件 … 在语句行尾端表示该行未完 ! 调用操作系统的命令 isvarname 判断变量名是否有效 声明全局变量 变量名前加 ...
- LuoguP3254 圆桌问题(最大流)
题目描述 假设有来自m 个不同单位的代表参加一次国际会议.每个单位的代表数分别为ri (i =1,2,……,m). 会议餐厅共有n 张餐桌,每张餐桌可容纳ci (i =1,2,……,n)个代表就餐. ...
- VMwarep挂载镜像及配置本地Yum源
1.挂载镜像: *. 通过mount命令 linux mount挂载设备(u盘,光盘,iso等 )使用说明 *. 通过VMware的控制页面手工挂载 1.1 打开Vmware软 ...
- Myeclipse学习总结(2)——MyEclipse快捷键大全
1.ctrl+shift+R 打开资源 此组快捷键可以打开工程中任意一个文件,而本人只需按文件名或者mask名的字母顺序输入就会出现对应的文件或者在内容中某个关键字再按快捷键也可以的,例如:Custo ...
- 数字签名算法--3.ECDSA
package Imooc; import java.security.KeyFactory; import java.security.KeyPair; import java.security.K ...
- [Angular & Unit Testing] TestBed.get vs Injector
Both what "TestBed.get" & "injector" trying to do is get service for the tes ...