Java NIO框架--Netty4的简单示例
来源:互联网 发布:德云色衣服淘宝店网址 编辑:程序博客网 时间:2024/05/16 07:26
简介
相比Netty3, Netty4有很多显著的变化: NioEventLoopGroup
是一个处理I/O操作的多线程事件环。即为Netty4里的线程池,在3.x里,一个Channel
是由ChannelFactory
创建的,同时新创建的Channel
会自动注册到一个隐藏的I/O线程。 4.0使用新的名为EventLoopGroup
的接口来替换ChannelFactory
,它由一个或多个EventLoop
来构成。一个新的 Channel
不会自动注册到EventLoopGroup
,但用户可以显式调用EventLoopGroup.register()
来注册。在Server端的Bootstrap
参数中,有两个EventLoopGroup
,第一个通常称为’boss’,用于接收发来的连接请求。第二个称为’worker’,,用于处理boss接受并且注册给worker的连接中的信息。 ChannelInitializer
是一个特殊的handler,用于方便的配置用户自定义的handler实现,如代码中所示。在channelRegistered
的生命周期中会触发用户复写的initChannel(C ch)
方法,并且在调用后会讲自身从channelPipeline
中移除。
代码示例
import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.codec.serialization.ClassResolvers;import io.netty.handler.codec.serialization.ObjectDecoder;import io.netty.handler.codec.serialization.ObjectEncoder;import io.netty.handler.logging.LogLevel;import io.netty.handler.logging.LoggingHandler;import io.netty.handler.ssl.SslContext;import io.netty.handler.ssl.util.SelfSignedCertificate;public class HelloWorldServer { static final boolean SSL = System.getProperty("ssl") != null; static final int PORT = Integer.parseInt(System.getProperty("port", "8007")); public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast( new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new HelloWorldServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }}class HelloWorldServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ctx.write("server write msg:"+msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); }}
import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.serialization.ClassResolvers;import io.netty.handler.codec.serialization.ObjectDecoder;import io.netty.handler.codec.serialization.ObjectEncoder;import io.netty.handler.ssl.SslContext;import io.netty.handler.ssl.util.InsecureTrustManagerFactory;public class HelloWorldClient { static final boolean SSL = System.getProperty("ssl") != null; static final String HOST = System.getProperty("host", "127.0.0.1"); static final int PORT = Integer.parseInt(System.getProperty("port", "8007")); public static void main(String[] args) throws Exception { // Configure SSL.git final SslContext sslCtx; if (SSL) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT)); } p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new HelloWorldClientHandler()); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }}class HelloWorldClientHandler extends ChannelInboundHandlerAdapter { private final String msg = "hello java world"; /** * Creates a client-side handler. */ public HelloWorldClientHandler() { //TODO } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(msg); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println(msg); // ctx.write(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); }}
0 0
- Java NIO框架--Netty4的简单示例
- Java NIO框架--Netty4的简单示例
- Java NIO框架Netty教程(十七) Netty4 Hello world
- java nio socket简单示例
- JAVA NIO的示例
- java的nio框架
- java nio socket通信简单入门示例
- 【Netty4 简单项目实践】九、示例项目
- Java NIO框架Netty1简单发送接受
- Java NIO框架Netty简单使用
- Netty4框架的初步使用
- NIO 框架Netty4.x 整体流程和使用
- Java NIO的简单介绍
- 技术贴:java nio的示例
- java:NIO读写文件的示例
- java nio 的读写操作代码示例
- java注解入门的简单介绍与示例(框架基础)
- Netty4实战第一章:Netty和Java NIO APIs
- 制作Mac U盘启动盘
- 开发优化-经理优化
- pthread_exit(void *rval_ptr)和pthread_join(pthread_t thread, void **rval_ptr)
- 规则引擎drools
- 使用CSV文件处理EXcel数据
- Java NIO框架--Netty4的简单示例
- 美团字典序笔试题
- git coding 代码备份库 简单命令使用
- 1.3:Union-Find算法-----quick-union算法的改进(加权的quick-union算法)
- 【codevs2293】山海经 线段树
- 第二章 学习CC3200输入和中断
- 使用struts2生成图片验证码并显示
- corethink功能模块探索开发(二)让这个模块可安装
- 深入JVM彻底剖析前面ygc越来越慢的case