netty3入门案例

Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络服务器和客户端程序。也就是说它是一个NIO框架,使用它可以简单快速地开发网络应用程序。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。学习netty前需要对NIO理解得很透彻,可参考我另一篇文章java NIO或者网上找资料学习一下。

下面分别以类似HelloWorld的最基础案例来学习,案例是基于网络通信的。所以有Server端和Client端,当然客户端可以在本地使用telnet命令来测试。netty3和netty5版本在API上区别较大,下面是Netty3的一个例子。

Netty3 Server:

 

[java] view plain copy

  1. public class Server {  
  2.     public static void main(String[] args) {  
  3.         // 服务类,用于启动netty 在netty5中同样使用这个类来启动  
  4.         ServerBootstrap bootstrap = new ServerBootstrap();  
  5.         // 新建两个线程池  boss线程监听端口,worker线程负责数据读写  
  6.         ExecutorService boss = Executors.newCachedThreadPool();  
  7.         ExecutorService worker = Executors.newCachedThreadPool();  
  8.         // 设置niosocket工厂  类似NIO程序新建ServerSocketChannel和SocketChannel  
  9.         bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));  
  10.         // 设置管道的工厂  
  11.         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
  12.             @Override  
  13.             public ChannelPipeline getPipeline() throws Exception {  
  14.                 ChannelPipeline pipeline = Channels.pipeline();  
  15.                 pipeline.addLast("decoder", new StringDecoder());  
  16.                 pipeline.addLast("encoder", new StringEncoder());  
  17.                 pipeline.addLast("helloHandler", new HelloHandler());  //添加一个Handler来处理客户端的事件,Handler需要继承ChannelHandler  
  18.                 return pipeline;  
  19.             }  
  20.         });  
  21.         bootstrap.bind(new InetSocketAddress(10101));  
  22.         System.out.println("start!!!");  
  23.     }  
  24. }  

HelloHandler类:

 

 

[java] view plain copy

  1. public class HelloHandler extends SimpleChannelHandler {  
  2.     /** 接收消息*/  
  3.     @Override  
  4.     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
  5.         String s = (String) e.getMessage();  
  6.         System.out.println(s);  
  7.         //回写数据  
  8.         ctx.getChannel().write("HelloWorld");  
  9.         super.messageReceived(ctx, e);  
  10.     }  
  11.     /** 捕获异常*/  
  12.     @Override  
  13.     public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {  
  14.         System.out.println("exceptionCaught");  
  15.         super.exceptionCaught(ctx, e);  
  16.     }  
  17.     /** 新连接*/  
  18.     @Override  
  19.     public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
  20.         System.out.println("channelConnected");  
  21.         super.channelConnected(ctx, e);  
  22.     }  
  23.     /** 必须是链接已经建立,关闭通道的时候才会触发  */  
  24.     @Override  
  25.     public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
  26.         System.out.println("channelDisconnected");  
  27.         super.channelDisconnected(ctx, e);  
  28.     }  
  29.     /** channel关闭的时候触发 */  
  30.     @Override  
  31.     public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
  32.         System.out.println("channelClosed");  
  33.         super.channelClosed(ctx, e);  
  34.     }  
  35. }  

到这里就可以启动Server端了。

 

netty3 Client:

[java] view plain copy

  1. public class Client {  
  2.     public static void main(String[] args) {  
  3.         // 客户端的启动类  
  4.         ClientBootstrap bootstrap = new  ClientBootstrap();  
  5.         //线程池  
  6.         ExecutorService boss = Executors.newCachedThreadPool();  
  7.         ExecutorService worker = Executors.newCachedThreadPool();  
  8.         //socket工厂  
  9.         bootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));  
  10.         //管道工厂  
  11.         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
  12.             @Override  
  13.             public ChannelPipeline getPipeline() throws Exception {  
  14.                 ChannelPipeline pipeline = Channels.pipeline();  
  15.                 pipeline.addLast("decoder", new StringDecoder());  
  16.                 pipeline.addLast("encoder", new StringEncoder());  
  17.                 pipeline.addLast("hiHandler", new HiHandler());  
  18.                 return pipeline;  
  19.             }  
  20.         });  
  21.         //连接服务端  
  22.         ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 10101));  
  23.         Channel channel = connect.getChannel();  
  24.         System.out.println("client start");  
  25.         Scanner scanner = new Scanner(System.in);  
  26.         while(true){  
  27.             System.out.println("请输入");  
  28.             channel.write(scanner.next());  
  29.         }  
  30.     }  
  31. }  

客户端不断等待终端输入并写入通道。服务端接收到新的输入后会获取到输入的信息。对服务端的回写客户端也需要一个Handler来处理。下面是这客户端HiHandler的代码

 

 

[java] view plain copy

  1. public class HiHandler extends SimpleChannelHandler {  
  2.     /** 接收消息*/  
  3.     @Override  
  4.     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
  5.         String s = (String) e.getMessage();  
  6.         System.out.println(s);  
  7.         super.messageReceived(ctx, e);  
  8.     }  
  9.     /** 捕获异常*/  
  10.     @Override  
  11.     public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {  
  12.         System.out.println("exceptionCaught");  
  13.         super.exceptionCaught(ctx, e);  
  14.     }  
  15.     /** 新连接*/  
  16.     @Override  
  17.     public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
  18.         System.out.println("channelConnected");  
  19.         super.channelConnected(ctx, e);  
  20.     }  
  21.     /** 必须是链接已经建立,关闭通道的时候才会触发*/  
  22.     @Override  
  23.     public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
  24.         System.out.println("channelDisconnected");  
  25.         super.channelDisconnected(ctx, e);  
  26.     }  
  27.     /** channel关闭的时候触发*/  
  28.     @Override  
  29.     public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
  30.         System.out.println("channelClosed");  
  31.         super.channelClosed(ctx, e);  
  32.     }  
  33. }  

至此就完成了Netty3的一个最基础的例子。

转载于:https://my.oschina.net/sniperLi/blog/913455

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值