http://blog.csdn.net/anxpp/article/details/52108238

Java NIO框架Netty简单使用 http://blog.csdn.net/anxpp/article/details/52108238



关闭
 

Java NIO框架Netty简单使用

  3866人阅读  评论(3)  收藏  举报
  分类:

转载请注明出处:http://blog.csdn.net/anxpp/article/details/52108238,谢谢!

    之前写了一篇文章:Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码),介绍了如何使用Java原生IO支持进行网络编程,本文介绍一种更为简单的方式,即Java NIO框架。

    Netty是业界最流行的NIO框架之一,具有良好的健壮性、功能、性能、可定制性和可扩展性。同时,它提供的十分简单的API,大大简化了我们的网络编程。

    同Java IO介绍的文章一样,本文所展示的例子,实现了一个相同的功能。

1、服务端

    Server:

[java]  view plain  copy
 print ?
  1. package com.anxpp.io.calculator.netty;  
  2. import io.netty.bootstrap.ServerBootstrap;  
  3. import io.netty.channel.ChannelFuture;  
  4. import io.netty.channel.ChannelInitializer;  
  5. import io.netty.channel.ChannelOption;  
  6. import io.netty.channel.EventLoopGroup;  
  7. import io.netty.channel.nio.NioEventLoopGroup;  
  8. import io.netty.channel.socket.SocketChannel;  
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  10. public class Server {  
  11.     private int port;  
  12.     public Server(int port) {  
  13.         this.port = port;  
  14.     }  
  15.     public void run() throws Exception {  
  16.         EventLoopGroup bossGroup = new NioEventLoopGroup();  
  17.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  18.         try {  
  19.             ServerBootstrap b = new ServerBootstrap();  
  20.             b.group(bossGroup, workerGroup)  
  21.              .channel(NioServerSocketChannel.class)  
  22.              .option(ChannelOption.SO_BACKLOG, 1024)  
  23.              .childOption(ChannelOption.SO_KEEPALIVE, true)  
  24.              .childHandler(new ChannelInitializer<SocketChannel>() {  
  25.                  @Override  
  26.                  public void initChannel(SocketChannel ch) throws Exception {  
  27.                      ch.pipeline().addLast(new ServerHandler());  
  28.                  }  
  29.              });  
  30.             ChannelFuture f = b.bind(port).sync();  
  31.             System.out.println("服务器开启:"+port);  
  32.             f.channel().closeFuture().sync();  
  33.         } finally {  
  34.             workerGroup.shutdownGracefully();  
  35.             bossGroup.shutdownGracefully();  
  36.         }  
  37.     }  
  38.     public static void main(String[] args) throws Exception {  
  39.         int port;  
  40.         if (args.length > 0) {  
  41.             port = Integer.parseInt(args[0]);  
  42.         } else {  
  43.             port = 9090;  
  44.         }  
  45.         new Server(port).run();  
  46.     }  
  47. }  

    ServerHandler:

[java]  view plain  copy
 print ?
  1. package com.anxpp.io.calculator.netty;  
  2. import io.netty.buffer.ByteBuf;  
  3. import io.netty.buffer.Unpooled;  
  4. import io.netty.channel.ChannelHandlerContext;  
  5. import io.netty.channel.ChannelInboundHandlerAdapter;  
  6. import java.io.UnsupportedEncodingException;  
  7. import com.anxpp.io.utils.Calculator;  
  8. public class ServerHandler extends ChannelInboundHandlerAdapter {  
  9.     @Override  
  10.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {  
  11.         ByteBuf in = (ByteBuf) msg;  
  12.         byte[] req = new byte[in.readableBytes()];  
  13.         in.readBytes(req);  
  14.         String body = new String(req,"utf-8");  
  15.         System.out.println("收到客户端消息:"+body);  
  16.         String calrResult = null;  
  17.         try{  
  18.             calrResult = Calculator.Instance.cal(body).toString();  
  19.         }catch(Exception e){  
  20.             calrResult = "错误的表达式:" + e.getMessage();  
  21.         }  
  22.         ctx.write(Unpooled.copiedBuffer(calrResult.getBytes()));  
  23.     }  
  24.     @Override  
  25.     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {  
  26.         ctx.flush();  
  27.     }  
  28.     /** 
  29.      * 异常处理 
  30.      */  
  31.     @Override  
  32.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {  
  33.         cause.printStackTrace();  
  34.         ctx.close();  
  35.     }  
  36. }  

2、客户端

    Client:

[java]  view plain  copy
 print ?
  1. <li class="alt" style="margin: 0px !important; padding: 0px 3px 0px 10px !important; border-top: none; border-right: none; border-bottom: none; border-left: 3px solid rgb(153, 153, 153); border-image: initial; list-style-type: decimal-leading-zero; list-style-image: initial; color: rgb(238, 238,%
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值