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 ...
随机推荐
- 位运算(&、|、^)与逻辑运算(&&、 ||)差别
刚无意在一篇文章中看到了位运算(&.|)和逻辑运算(&&.||)的介绍.想起了自己薄弱的基础知识.于是百度了几把总结了下. 首先从概念上区分下,位运算是将运算符两边的数字换算成 ...
- 使用PHP来压缩CSS文件
这里将介绍使用PHP以一种简便的方式来压缩你的CSS文件.这种方法不需要命名你的.css文件和.php文件. 当前有许多方法需要将.css文件重命名成.php文件,然后在所有PHP文件中放置压缩代码. ...
- POJ 2437 贪心+priority_queue
题意: 思路: 贪心 能不覆盖的就不盖 写得很乱 左闭右开的 temp //By SiriusRen #include <queue> #include <cstdio> #i ...
- #学习记录#——CSS content 属性
CSS content 属性常结合:before 和:after 这两个伪类一起使用,给指定的元素添加内容来丰富页面. 1. 添加文本内容 html: <h1>给末尾添加内容. </ ...
- Vectorized implementation
Vectorization Vectorization refers to a powerful way to speed up your algorithms. Numerical computin ...
- C/C++(文件操作二)
二进制读写才是本质 二进制的读写对文件标记不敏感. eg: 对图片进行加密与解密: 用命令的形式去执行: //xx.exe -c src dest 加密 //xx.exe -d src dest 解密 ...
- ManagementObjectSearcher 对象获取串口列表
首先,需引用using System.Management; 可先建个枚举类,如下 #region WIN32 API /// <summary> /// 枚举win32 api /// ...
- CODEVS——T 3013 单词背诵
http://codevs.cn/problem/3013/ 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题解 查看运行结果 题目描述 De ...
- HDU——T 1573 X问题
http://acm.hdu.edu.cn/showproblem.php?pid=1573 Time Limit: 1000/1000 MS (Java/Others) Memory Limi ...
- Google、Mozilla、Qt、LLVM 这几家的规范是明确禁用异常的
作者:陈硕链接:https://www.zhihu.com/question/22889420/answer/22975569来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出 ...