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

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

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

你可能感兴趣的:(Android,Java)