`
irfen
  • 浏览: 202723 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Netty学习(2)——Netty使用实例

 
阅读更多

以下两个例子基于netty-3.5.7.Final.jar用Junit进行测试

 

第一个例子:简单的发送字符串,接收字符串“Hello, World”

 

Java代码  
  1. class HelloWorldServerHandler extends SimpleChannelHandler {  
  2.     public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)  
  3.             throws Exception {  
  4.         e.getChannel().write("Hello, World");  
  5.     }  
  6.   
  7.     public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {  
  8.         System.out.println("Unexpected exception from downstream."  
  9.                 + e.getCause());  
  10.         e.getChannel().close();  
  11.     }  
  12. }  
  13.   
  14. class HelloWorldClientHandler extends SimpleChannelHandler {  
  15.   
  16.     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {  
  17.         String message = (String) e.getMessage();  
  18.         System.out.println(message);  
  19.         e.getChannel().close();  
  20.     }  
  21.   
  22.     public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {  
  23.         System.out.println("Unexpected exception from downstream."  
  24.                 + e.getCause());  
  25.         e.getChannel().close();  
  26.     }  
  27. }  
  28.   
  29.   
  30. /** 
  31.  * Netty VS MinaNetty基于Pipeline处理,Mina基于Filter过滤 
  32.  * Netty的事件驱动模型具有更好的扩展性和易用性 
  33.  * Https,SSL,PB,RSTP,Text &Binary等协议支持 
  34.  * Netty中UDP传输有更好的支持官方测试Netty比Mina性能更好 
  35.  * @author Administrator 
  36.  * 
  37.  */  
  38. public class TestCase {  
  39.   
  40.     public void testServer() {  
  41.         //初始化channel的辅助类,为具体子类提供公共数据结构  
  42.         ServerBootstrap bootstrap = new ServerBootstrap(  
  43.                 new NioServerSocketChannelFactory(  
  44.                         Executors.newCachedThreadPool(),  
  45.                         Executors.newCachedThreadPool()));  
  46.         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
  47.             public ChannelPipeline getPipeline() {  
  48.                 ChannelPipeline pipeline = Channels.pipeline();  
  49.                 pipeline.addLast("decoder"new StringDecoder());  
  50.                 pipeline.addLast("encoder"new StringEncoder());  
  51.                 pipeline.addLast("handler"new HelloWorldServerHandler());  
  52.                 return pipeline;  
  53.             }  
  54.         });  
  55.         //创建服务器端channel的辅助类,接收connection请求  
  56.         bootstrap.bind(new InetSocketAddress(8080));  
  57.     }  
  58.       
  59.       
  60.       
  61.     public void testClient() {  
  62.         //创建客户端channel的辅助类,发起connection请求   
  63.         ClientBootstrap bootstrap = new ClientBootstrap(  
  64.                 new NioClientSocketChannelFactory(  
  65.                         Executors.newCachedThreadPool(),  
  66.                         Executors.newCachedThreadPool()));  
  67.         //It means one same HelloWorldClientHandler instance is going to handle multiple Channels and consequently the data will be corrupted.  
  68.         //基于上面这个描述,必须用到ChannelPipelineFactory每次创建一个pipeline  
  69.         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
  70.             public ChannelPipeline getPipeline() {  
  71.                 ChannelPipeline pipeline =  Channels.pipeline();  
  72.                 pipeline.addLast("decoder"new StringDecoder());  
  73.                 pipeline.addLast("encoder"new StringEncoder());  
  74.                 pipeline.addLast("handler"new HelloWorldClientHandler());  
  75.                 return pipeline;  
  76.             }  
  77.         });  
  78.         //创建无连接传输channel的辅助类(UDP),包括client和server  
  79.         ChannelFuture future = bootstrap.connect(new InetSocketAddress(  
  80.                 "localhost"8080));  
  81.         future.getChannel().getCloseFuture().awaitUninterruptibly();  
  82.         bootstrap.releaseExternalResources();  
  83.     }  
  84.       
  85.       
  86.     @Test  
  87.     public void testNetty(){  
  88.         testServer();  
  89.         testClient();  
  90.     }  
  91.   
  92. }  

 

 第二个例子,实际应用中会用到这个,发送POJO类Persons [name=周杰伦123, age=31, salary=10000.44]

 

Java代码  
  1. /** 
  2.  * 用POJO代替ChannelBuffer 
  3.  */  
  4.   
  5. class TimeServerHandler3 extends SimpleChannelHandler {    
  6.         
  7.     @Override    
  8.     public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)    
  9.             throws Exception {    
  10.         Persons person = new Persons("周杰伦123",31,10000.44);  
  11.         ChannelFuture future = e.getChannel().write(person);    
  12.         future.addListener(ChannelFutureListener.CLOSE);    
  13.     }    
  14. }    
  15.   
  16. class TimeClientHandler3 extends SimpleChannelHandler{    
  17.         
  18.     @Override    
  19.     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)    
  20.             throws Exception {    
  21.         Persons person = (Persons)e.getMessage();    
  22.         System.out.println(person);    
  23.         e.getChannel().close();    
  24.     }    
  25. }  
  26.   
  27. /** 
  28.  * FrameDecoder and ReplayingDecoder allow you to return an object of any type. 
  29.  *  
  30.  */  
  31. class TimeDecoder extends FrameDecoder {    
  32.     private final ChannelBuffer buffer = dynamicBuffer();  
  33.         
  34.     @Override    
  35.     protected Object decode(ChannelHandlerContext ctx, Channel channel,    
  36.             ChannelBuffer channelBuffer) throws Exception {    
  37.         if(channelBuffer.readableBytes()<4) {    
  38.             return null;    
  39.         }    
  40.         if (channelBuffer.readable()) {  
  41.             // 读到,并写入buf  
  42.             channelBuffer.readBytes(buffer, channelBuffer.readableBytes());  
  43.         }  
  44.         int namelength = buffer.readInt();  
  45.         String name = new String(buffer.readBytes(namelength).array(),"GBK");  
  46.         int age = buffer.readInt();  
  47.         double salary = buffer.readDouble();  
  48.         Persons person = new Persons(name,age,salary);  
  49.         return person;    
  50.     }    
  51.     
  52. }    
  53.   
  54. class TimeEncoder extends SimpleChannelHandler {    
  55.     private final ChannelBuffer buffer = dynamicBuffer();  
  56.       
  57.     @Override    
  58.     public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)    
  59.             throws Exception {    
  60.         Persons person = (Persons)e.getMessage();    
  61.         buffer.writeInt(person.getName().getBytes("GBK").length);  
  62.         buffer.writeBytes(person.getName().getBytes("GBK"));  
  63.         buffer.writeInt(person.getAge());  
  64.         buffer.writeDouble(person.getSalary());  
  65.         Channels.write(ctx, e.getFuture(), buffer);    
  66.     }    
  67. }  
  68.   
  69. class Persons{  
  70.     private String name;  
  71.     private int age;  
  72.     private double salary;  
  73.       
  74.     public Persons(String name,int age,double salary){  
  75.         this.name = name;  
  76.         this.age = age;  
  77.         this.salary = salary;  
  78.     }  
  79.       
  80.     public String getName() {  
  81.         return name;  
  82.     }  
  83.     public void setName(String name) {  
  84.         this.name = name;  
  85.     }  
  86.     public int getAge() {  
  87.         return age;  
  88.     }  
  89.     public void setAge(int age) {  
  90.         this.age = age;  
  91.     }  
  92.     public double getSalary() {  
  93.         return salary;  
  94.     }  
  95.     public void setSalary(double salary) {  
  96.         this.salary = salary;  
  97.     }  
  98.   
  99.     @Override  
  100.     public String toString() {  
  101.         return "Persons [name=" + name + ", age=" + age + ", salary=" + salary  
  102.                 + "]";  
  103.     }  
  104.       
  105.       
  106. }  
  107.   
  108. public class TestCase5 {  
  109.     public void testServer() {  
  110.           ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());    
  111.             ServerBootstrap bootstrap = new ServerBootstrap(factory);    
  112.             bootstrap.setPipelineFactory(new ChannelPipelineFactory() {    
  113.                     
  114.                 public ChannelPipeline getPipeline() throws Exception {    
  115.                     return Channels.pipeline(new TimeEncoder(), new TimeServerHandler3());    
  116.                 }    
  117.             });    
  118.             bootstrap.setOption("child.tcpNoDelay"true);    
  119.             bootstrap.setOption("child.keepAlive"true);    
  120.                 
  121.             bootstrap.bind(new InetSocketAddress("localhost",9999));   
  122.     }  
  123.       
  124.     public void testClient(){  
  125.         //创建客户端channel的辅助类,发起connection请求   
  126.         ClientBootstrap bootstrap = new ClientBootstrap(  
  127.                 new NioClientSocketChannelFactory(  
  128.                         Executors.newCachedThreadPool(),  
  129.                         Executors.newCachedThreadPool()));  
  130.         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
  131.             public ChannelPipeline getPipeline() {  
  132.                 ChannelPipeline pipeline =  Channels.pipeline();  
  133.                 pipeline.addLast("decoder"new TimeDecoder());  
  134.                 pipeline.addLast("encoder"new TimeEncoder());  
  135.                 pipeline.addLast("handler"new TimeClientHandler3());  
  136.                 return pipeline;  
  137.             }  
  138.         });  
  139.         //创建无连接传输channel的辅助类(UDP),包括client和server  
  140.         ChannelFuture future = bootstrap.connect(new InetSocketAddress(  
  141.                 "localhost"9999));  
  142.         future.getChannel().getCloseFuture().awaitUninterruptibly();  
  143.         bootstrap.releaseExternalResources();  
  144.     }  
  145.   
  146.     @Test  
  147.     public void testNetty() {  
  148.             testServer();  
  149.             testClient();  
  150.     }  
  151. }  

 

这两段代码是学习的时候参考别人的代码,转于哪想不起来了,但是这两段代码让我了解了netty的通信流程。

1
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics