netty4.0.23 初学的demo



netty4.0.23 初学的demo

 

例子共4个文件,用到的jar包有:

netty-all-4.0.23.Final.jar

log4j.jar (apache的)

commons-logging-1.1.1.jar(apache的)

 

文件 TcpServerHandler

 

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.SimpleChannelInboundHandler;  
  7.   
  8. public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {  
  9.   
  10.     private static final Logger logger = Logger.getLogger(TcpServerHandler.class);  
  11.   
  12.     @Override  
  13.     protected void channelRead0(ChannelHandlerContext ctx, Object msg)  
  14.             throws Exception {  
  15.         logger.info("SERVER接收到消息:"+msg);  
  16.         ctx.channel().writeAndFlush("yes, server is accepted you ,nice !"+msg);  
  17.     }  
  18.       
  19.     @Override  
  20.     public void exceptionCaught(ChannelHandlerContext ctx,  
  21.             Throwable cause) throws Exception {  
  22.         logger.warn("Unexpected exception from downstream.", cause);  
  23.         ctx.close();  
  24.     }  
  25.   
  26. }  

 

 

文件 TcpServer

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.bootstrap.ServerBootstrap;  
  6. import io.netty.channel.ChannelInitializer;  
  7. import io.netty.channel.ChannelPipeline;  
  8. import io.netty.channel.EventLoopGroup;  
  9. import io.netty.channel.nio.NioEventLoopGroup;  
  10. import io.netty.channel.socket.SocketChannel;  
  11. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  12. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  13. import io.netty.handler.codec.LengthFieldPrepender;  
  14. import io.netty.handler.codec.string.StringDecoder;  
  15. import io.netty.handler.codec.string.StringEncoder;  
  16. import io.netty.util.CharsetUtil;  
  17.   
  18. public class TcpServer {  
  19.   
  20.     private static final Logger logger = Logger.getLogger(TcpServer.class);  
  21.     private static final String IP = "127.0.0.1";  
  22.     private static final int PORT = 9999;  
  23.     /**用于分配处理业务线程的线程组个数 */  
  24.     protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2//默认  
  25.     /** 业务出现线程大小*/  
  26.     protected static final int BIZTHREADSIZE = 4;  
  27.         /* 
  28.      * NioEventLoopGroup实际上就是个线程池, 
  29.      * NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件, 
  30.      * 每一个NioEventLoop负责处理m个Channel, 
  31.      * NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel 
  32.      */  
  33.     private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);  
  34.     private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);  
  35.       
  36.     protected static void run() throws Exception {  
  37.         ServerBootstrap b = new ServerBootstrap();  
  38.         b.group(bossGroup, workerGroup);  
  39.         b.channel(NioServerSocketChannel.class);  
  40.         b.childHandler(new ChannelInitializer<SocketChannel>() {  
  41.             @Override  
  42.             public void initChannel(SocketChannel ch) throws Exception {  
  43.                 ChannelPipeline pipeline = ch.pipeline();  
  44.                 pipeline.addLast("frameDecoder"new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0404));  
  45.                 pipeline.addLast("frameEncoder"new LengthFieldPrepender(4));  
  46.                 pipeline.addLast("decoder"new StringDecoder(CharsetUtil.UTF_8));  
  47.                 pipeline.addLast("encoder"new StringEncoder(CharsetUtil.UTF_8));  
  48.                 pipeline.addLast(new TcpServerHandler());  
  49.             }  
  50.         });  
  51.   
  52.         b.bind(IP, PORT).sync();  
  53.         logger.info("TCP服务器已启动");  
  54.     }  
  55.       
  56.     protected static void shutdown() {  
  57.         workerGroup.shutdownGracefully();  
  58.         bossGroup.shutdownGracefully();  
  59.     }  
  60.   
  61.     public static void main(String[] args) throws Exception {  
  62.         logger.info("开始启动TCP服务器...");  
  63.         TcpServer.run();  
  64. //      TcpServer.shutdown();  
  65.     }  
  66. }  

 

文件 TcpClientHandler

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.SimpleChannelInboundHandler;  
  7.   
  8. public class TcpClientHandler extends SimpleChannelInboundHandler<Object> {  
  9.   
  10.     private static final Logger logger = Logger.getLogger(TcpClientHandler.class);  
  11.   
  12.     @Override  
  13.     protected void channelRead0(ChannelHandlerContext ctx, Object msg)  
  14.             throws Exception {  
  15.         //messageReceived方法,名称很别扭,像是一个内部方法.  
  16.         logger.info("client接收到服务器返回的消息:"+msg);  
  17.           
  18.     }  
  19.   
  20. }  

 

文件 TcpClient

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import io.netty.bootstrap.Bootstrap;  
  4. import io.netty.channel.Channel;  
  5. import io.netty.channel.ChannelInitializer;  
  6. import io.netty.channel.ChannelOption;  
  7. import io.netty.channel.ChannelPipeline;  
  8. import io.netty.channel.EventLoopGroup;  
  9. import io.netty.channel.nio.NioEventLoopGroup;  
  10. import io.netty.channel.socket.nio.NioSocketChannel;  
  11. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  12. import io.netty.handler.codec.LengthFieldPrepender;  
  13. import io.netty.handler.codec.string.StringDecoder;  
  14. import io.netty.handler.codec.string.StringEncoder;  
  15. import io.netty.util.CharsetUtil;  
  16.   
  17. import org.apache.log4j.Logger;  
  18.   
  19. public class TcpClient {  
  20.     private static final Logger logger = Logger.getLogger(TcpClient.class);  
  21.     public static String HOST = "127.0.0.1";  
  22.     public static int PORT = 9999;  
  23.       
  24.     public static Bootstrap bootstrap = getBootstrap();  
  25.     public static Channel channel = getChannel(HOST,PORT);  
  26.     /** 
  27.      * 初始化Bootstrap 
  28.      * @return 
  29.      */  
  30.     public static final Bootstrap getBootstrap(){  
  31.         EventLoopGroup group = new NioEventLoopGroup();  
  32.         Bootstrap b = new Bootstrap();  
  33.         b.group(group).channel(NioSocketChannel.class);  
  34.         b.handler(new ChannelInitializer<Channel>() {  
  35.             @Override  
  36.             protected void initChannel(Channel ch) throws Exception {  
  37.                 ChannelPipeline pipeline = ch.pipeline();  
  38.                 pipeline.addLast("frameDecoder"new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0404));  
  39.                 pipeline.addLast("frameEncoder"new LengthFieldPrepender(4));  
  40.                 pipeline.addLast("decoder"new StringDecoder(CharsetUtil.UTF_8));  
  41.                 pipeline.addLast("encoder"new StringEncoder(CharsetUtil.UTF_8));  
  42.                 pipeline.addLast("handler"new TcpClientHandler());  
  43.             }  
  44.         });  
  45.         b.option(ChannelOption.SO_KEEPALIVE, true);  
  46.         return b;  
  47.     }  
  48.   
  49.     public static final Channel getChannel(String host,int port){  
  50.         Channel channel = null;  
  51.         try {  
  52.             channel = bootstrap.connect(host, port).sync().channel();  
  53.         } catch (Exception e) {  
  54.             logger.error(String.format("连接Server(IP[%s],PORT[%s])失败", host,port),e);  
  55.             return null;  
  56.         }  
  57.         return channel;  
  58.     }  
  59.   
  60.     public static void sendMsg(String msg) throws Exception {  
  61.         if(channel!=null){  
  62.             channel.writeAndFlush(msg).sync();  
  63.         }else{  
  64.             logger.warn("消息发送失败,连接尚未建立!");  
  65.         }  
  66.     }  
  67.   
  68.     public static void main(String[] args) throws Exception {  
  69.         try {  
  70.             long t0 = System.nanoTime();  
  71.             for (int i = 0; i < 100000; i++) {  
  72.                 TcpClient.sendMsg(i+"你好1");  
  73.             }  
  74.             long t1 = System.nanoTime();  
  75.             System.out.println((t1-t0)/1000000.0);  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80. }  

 

 

netty4.0.23 初学的demo

 

例子共4个文件,用到的jar包有:

netty-all-4.0.23.Final.jar

log4j.jar (apache的)

commons-logging-1.1.1.jar(apache的)

 

文件 TcpServerHandler

 

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.SimpleChannelInboundHandler;  
  7.   
  8. public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {  
  9.   
  10.     private static final Logger logger = Logger.getLogger(TcpServerHandler.class);  
  11.   
  12.     @Override  
  13.     protected void channelRead0(ChannelHandlerContext ctx, Object msg)  
  14.             throws Exception {  
  15.         logger.info("SERVER接收到消息:"+msg);  
  16.         ctx.channel().writeAndFlush("yes, server is accepted you ,nice !"+msg);  
  17.     }  
  18.       
  19.     @Override  
  20.     public void exceptionCaught(ChannelHandlerContext ctx,  
  21.             Throwable cause) throws Exception {  
  22.         logger.warn("Unexpected exception from downstream.", cause);  
  23.         ctx.close();  
  24.     }  
  25.   
  26. }  

 

 

文件 TcpServer

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.bootstrap.ServerBootstrap;  
  6. import io.netty.channel.ChannelInitializer;  
  7. import io.netty.channel.ChannelPipeline;  
  8. import io.netty.channel.EventLoopGroup;  
  9. import io.netty.channel.nio.NioEventLoopGroup;  
  10. import io.netty.channel.socket.SocketChannel;  
  11. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  12. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  13. import io.netty.handler.codec.LengthFieldPrepender;  
  14. import io.netty.handler.codec.string.StringDecoder;  
  15. import io.netty.handler.codec.string.StringEncoder;  
  16. import io.netty.util.CharsetUtil;  
  17.   
  18. public class TcpServer {  
  19.   
  20.     private static final Logger logger = Logger.getLogger(TcpServer.class);  
  21.     private static final String IP = "127.0.0.1";  
  22.     private static final int PORT = 9999;  
  23.     /**用于分配处理业务线程的线程组个数 */  
  24.     protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2//默认  
  25.     /** 业务出现线程大小*/  
  26.     protected static final int BIZTHREADSIZE = 4;  
  27.         /* 
  28.      * NioEventLoopGroup实际上就是个线程池, 
  29.      * NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件, 
  30.      * 每一个NioEventLoop负责处理m个Channel, 
  31.      * NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel 
  32.      */  
  33.     private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);  
  34.     private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);  
  35.       
  36.     protected static void run() throws Exception {  
  37.         ServerBootstrap b = new ServerBootstrap();  
  38.         b.group(bossGroup, workerGroup);  
  39.         b.channel(NioServerSocketChannel.class);  
  40.         b.childHandler(new ChannelInitializer<SocketChannel>() {  
  41.             @Override  
  42.             public void initChannel(SocketChannel ch) throws Exception {  
  43.                 ChannelPipeline pipeline = ch.pipeline();  
  44.                 pipeline.addLast("frameDecoder"new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0404));  
  45.                 pipeline.addLast("frameEncoder"new LengthFieldPrepender(4));  
  46.                 pipeline.addLast("decoder"new StringDecoder(CharsetUtil.UTF_8));  
  47.                 pipeline.addLast("encoder"new StringEncoder(CharsetUtil.UTF_8));  
  48.                 pipeline.addLast(new TcpServerHandler());  
  49.             }  
  50.         });  
  51.   
  52.         b.bind(IP, PORT).sync();  
  53.         logger.info("TCP服务器已启动");  
  54.     }  
  55.       
  56.     protected static void shutdown() {  
  57.         workerGroup.shutdownGracefully();  
  58.         bossGroup.shutdownGracefully();  
  59.     }  
  60.   
  61.     public static void main(String[] args) throws Exception {  
  62.         logger.info("开始启动TCP服务器...");  
  63.         TcpServer.run();  
  64. //      TcpServer.shutdown();  
  65.     }  
  66. }  

 

文件 TcpClientHandler

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.SimpleChannelInboundHandler;  
  7.   
  8. public class TcpClientHandler extends SimpleChannelInboundHandler<Object> {  
  9.   
  10.     private static final Logger logger = Logger.getLogger(TcpClientHandler.class);  
  11.   
  12.     @Override  
  13.     protected void channelRead0(ChannelHandlerContext ctx, Object msg)  
  14.             throws Exception {  
  15.         //messageReceived方法,名称很别扭,像是一个内部方法.  
  16.         logger.info("client接收到服务器返回的消息:"+msg);  
  17.           
  18.     }  
  19.   
  20. }  

 

文件 TcpClient

Java代码   收藏代码
  1. package test.netty;  
  2.   
  3. import io.netty.bootstrap.Bootstrap;  
  4. import io.netty.channel.Channel;  
  5. import io.netty.channel.ChannelInitializer;  
  6. import io.netty.channel.ChannelOption;  
  7. import io.netty.channel.ChannelPipeline;  
  8. import io.netty.channel.EventLoopGroup;  
  9. import io.netty.channel.nio.NioEventLoopGroup;  
  10. import io.netty.channel.socket.nio.NioSocketChannel;  
  11. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  12. import io.netty.handler.codec.LengthFieldPrepender;  
  13. import io.netty.handler.codec.string.StringDecoder;  
  14. import io.netty.handler.codec.string.StringEncoder;  
  15. import io.netty.util.CharsetUtil;  
  16.   
  17. import org.apache.log4j.Logger;  
  18.   
  19. public class TcpClient {  
  20.     private static final Logger logger = Logger.getLogger(TcpClient.class);  
  21.     public static String HOST = "127.0.0.1";  
  22.     public static int PORT = 9999;  
  23.       
  24.     public static Bootstrap bootstrap = getBootstrap();  
  25.     public static Channel channel = getChannel(HOST,PORT);  
  26.     /** 
  27.      * 初始化Bootstrap 
  28.      * @return 
  29.      */  
  30.     public static final Bootstrap getBootstrap(){  
  31.         EventLoopGroup group = new NioEventLoopGroup();  
  32.         Bootstrap b = new Bootstrap();  
  33.         b.group(group).channel(NioSocketChannel.class);  
  34.         b.handler(new ChannelInitializer<Channel>() {  
  35.             @Override  
  36.             protected void initChannel(Channel ch) throws Exception {  
  37.                 ChannelPipeline pipeline = ch.pipeline();  
  38.                 pipeline.addLast("frameDecoder"new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0404));  
  39.                 pipeline.addLast("frameEncoder"new LengthFieldPrepender(4));  
  40.                 pipeline.addLast("decoder"new StringDecoder(CharsetUtil.UTF_8));  
  41.                 pipeline.addLast("encoder"new StringEncoder(CharsetUtil.UTF_8));  
  42.                 pipeline.addLast("handler"new TcpClientHandler());  
  43.             }  
  44.         });  
  45.         b.option(ChannelOption.SO_KEEPALIVE, true);  
  46.         return b;  
  47.     }  
  48.   
  49.     public static final Channel getChannel(String host,int port){  
  50.         Channel channel = null;  
  51.         try {  
  52.             channel = bootstrap.connect(host, port).sync().channel();  
  53.         } catch (Exception e) {  
  54.             logger.error(String.format("连接Server(IP[%s],PORT[%s])失败", host,port),e);  
  55.             return null;  
  56.         }  
  57.         return channel;  
  58.     }  
  59.   
  60.     public static void sendMsg(String msg) throws Exception {  
  61.         if(channel!=null){  
  62.             channel.writeAndFlush(msg).sync();  
  63.         }else{  
  64.             logger.warn("消息发送失败,连接尚未建立!");  
  65.         }  
  66.     }  
  67.   
  68.     public static void main(String[] args) throws Exception {  
  69.         try {  
  70.             long t0 = System.nanoTime();  
  71.             for (int i = 0; i < 100000; i++) {  
  72.                 TcpClient.sendMsg(i+"你好1");  
  73.             }  
  74.             long t1 = System.nanoTime();  
  75.             System.out.println((t1-t0)/1000000.0);  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80. }  

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值