Netty 服务器客户端,发送自定义消息

时间:2022-12-06 08:55:26

Netty 5 的包



服务器,四个Java文件


1            SubReqServer.java

[java] view plain copy print?
  1. package com.test.netty;  
  2.   
  3. import io.netty.bootstrap.ServerBootstrap;  
  4. import io.netty.channel.ChannelFuture;  
  5. import io.netty.channel.ChannelInitializer;  
  6. import io.netty.channel.ChannelOption;  
  7. import io.netty.channel.EventLoopGroup;  
  8. import io.netty.channel.nio.NioEventLoopGroup;  
  9. import io.netty.channel.socket.SocketChannel;  
  10. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  11. import io.netty.handler.codec.serialization.ClassResolvers;  
  12. import io.netty.handler.codec.serialization.ObjectDecoder;  
  13. import io.netty.handler.codec.serialization.ObjectEncoder;  
  14. import io.netty.handler.logging.LogLevel;  
  15. import io.netty.handler.logging.LoggingHandler;  
  16.   
  17. public class SubReqServer {  
  18.       
  19.     public void bind(int nPort) throws Exception {  
  20.           
  21.         EventLoopGroup bossGroup = new NioEventLoopGroup();  
  22.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  23.                   
  24.         try{  
  25.             ServerBootstrap b = new ServerBootstrap();  
  26.             b.group(bossGroup, workerGroup)  
  27.             .channel(NioServerSocketChannel.class)  
  28.             .option(ChannelOption.SO_BACKLOG, 100)  
  29.             .handler(new LoggingHandler(LogLevel.INFO))  
  30.             .childHandler(new ChannelInitializer<SocketChannel>(){  
  31.                 @Override  
  32.                 public void initChannel(SocketChannel ch) throws Exception{  
  33.                     ch.pipeline()  
  34.                     .addLast(  
  35.                             new ObjectDecoder(1024*1024,  
  36.                                     ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())))  
  37.                     .addLast(new ObjectEncoder())  
  38.                     .addLast(new SubReqServerHandler());  
  39.                 }  
  40.             });  
  41.               
  42.             ChannelFuture f = b.bind(nPort).sync();  
  43.             System.out.println("---------------wait for connect");  
  44.             f.channel().closeFuture().sync();  
  45.         }finally {  
  46.             System.out.println("---------------wait for connect  Error!");  
  47.             bossGroup.shutdownGracefully();  
  48.             workerGroup.shutdownGracefully();  
  49.         }  
  50.     }  
  51.           
  52.       
  53.     public static void main(String[] args){  
  54.         int nPort = 5656;  
  55.         nPort = Integer.valueOf(nPort);  
  56.         System.out.println("---------------Main start");  
  57.         try {  
  58.             new SubReqServer().bind(nPort);  
  59.         } catch (Exception e) {  
  60.             System.out.println("---------------Main Error");  
  61.             e.printStackTrace();  
  62.         }  
  63.     }  
  64. }  




2            SubReqServerHandler.java


[java] view plain copy print?
  1. package com.test.netty;  
  2.   
  3. import io.netty.channel.ChannelHandlerAdapter;  
  4. import io.netty.channel.ChannelHandlerContext;  
  5.   
  6. public class SubReqServerHandler extends ChannelHandlerAdapter{  
  7.   
  8.     @Override  
  9.     public void channelActive(ChannelHandlerContext ctx){  
  10.         System.out.println("--------------------------------handler channelActive------------");  
  11.           
  12. //      for(int i = 0; i<10; i++){  
  13. //          SubscribeReq req = new SubscribeReq();  
  14. //          req.setAddress("深圳JJYY");  
  15. //          req.setPhoneNumber("13888886666");  
  16. //          req.setProductName("Netty Book");  
  17. //          req.setSubReqID(i);  
  18. //          req.setUserName("XXYY");  
  19. //          ctx.write(req);  
  20. //      }  
  21. //      ctx.flush();  
  22.     }  
  23.       
  24.     @Override  
  25.     public void channelRead(ChannelHandlerContext ctx, Object msg)  
  26.         throws Exception{  
  27.           
  28. //          SubscribeReq reqx = new SubscribeReq();  
  29. //          reqx.setAddress("*****深圳蛇口");  
  30. //          reqx.setPhoneNumber("13888886666");  
  31. //          reqx.setProductName("Netty Book");  
  32. //          reqx.setSubReqID(6666);  
  33. //          reqx.setUserName("XXYY");  
  34. //          ctx.write(reqx);  
  35. //          ctx.flush();  
  36. //        
  37.             SubscribeResp resp = new SubscribeResp();  
  38.             resp.setnSubReqID(555);  
  39.             resp.setRespCode(0);  
  40.             resp.setDesc("-------Netty book order succeed, 3days later, sent to the designated address");  
  41.             ctx.writeAndFlush(resp);    // 反馈消息  
  42.             //ctx.write(resp);  
  43.             //ctx.flush();  
  44.           
  45.             SubscribeReq req = (SubscribeReq)msg;   // 订购内容  
  46.             if("XXYY".equalsIgnoreCase(req.getUserName())){  
  47.                 System.out.println("接收到的数据: [  " + req.toString() + "   ]");  
  48.             }  
  49.               
  50.     }  
  51.       
  52.     @Override  
  53.     public  void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){  
  54.         System.out.println("---------------exceptionCaught 网络异常,关闭网络");  
  55.         cause.printStackTrace();  
  56.         ctx.close();  
  57.     }  
  58. }  





3            SubscribeReq.java


[java] view plain copy print?
  1. package com.test.netty;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class SubscribeReq  implements  Serializable{  
  6.       
  7.     private static final long nSerialVerUID = 1L;  
  8.     private int nSubReqID;  
  9.     private String strUserName;  
  10.     private String strProductName;  
  11.     private String strPhoneNumber;  
  12.       
  13.     private String strAddr;  
  14.       
  15.     public final int getSubReqID(){  
  16.         return nSubReqID;  
  17.     }  
  18.       
  19.     public final void setSubReqID(int nSubReqID){  
  20.         this.nSubReqID = nSubReqID;  
  21.     }  
  22.       
  23.     public final String getUserName(){  
  24.         return strUserName;  
  25.     }  
  26.       
  27.     public final void setUserName(String strUserName){  
  28.         this.strUserName = strUserName;  
  29.     }  
  30.       
  31.     public final String getProductName(){  
  32.         return strProductName;  
  33.     }  
  34.       
  35.     public final void setProductName(String strProductName){  
  36.         this.strProductName = strProductName;  
  37.     }  
  38.       
  39.     public final String getPhoneNumber(){  
  40.         return strPhoneNumber;  
  41.     }  
  42.       
  43.     public final void setPhoneNumber(String strPhoneNumber){  
  44.         this.strPhoneNumber = strPhoneNumber;  
  45.     }  
  46.       
  47.     public final String getAddress(){  
  48.         return strAddr;  
  49.     }  
  50.       
  51.     public final void setAddress(String strAddr){  
  52.         this.strAddr = strAddr;  
  53.     }  
  54.       
  55.       
  56.     @Override  
  57.     public String toString(){  
  58.         return "----SubscribeReq[subReqID="+ nSubReqID + ",userName="+ strUserName  
  59.                 +",productName="+strProductName+",phoneNumber="+strPhoneNumber  
  60.                 +",address"+strAddr+"]";  
  61.     }  
  62.       
  63.       
  64. }  




4            SubscribeResp.java



[java] view plain copy print?
  1. package com.test.netty;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class SubscribeResp implements Serializable{  
  6.     private static final long nSerialVerUID = 2L;  
  7.       
  8.      private int nSubReqID;  
  9.   
  10.         private int nRespCode;  
  11.   
  12.         private String strDesc;  
  13.   
  14.         public final int getnSubReqID() {  
  15.         return nSubReqID;  
  16.         }  
  17.   
  18.         public final void setnSubReqID(int nSubReqID) {  
  19.         this.nSubReqID = nSubReqID;  
  20.         }  
  21.   
  22.         public final int getnRespCode() {  
  23.         return nRespCode;  
  24.         }  
  25.   
  26.         public final void setRespCode(int nRespCode) {  
  27.         this.nRespCode = nRespCode;  
  28.         }  
  29.   
  30.         public final String getstrDesc() {  
  31.         return strDesc;  
  32.         }  
  33.   
  34.         public final void setDesc(String strDesc) {  
  35.         this.strDesc = strDesc;  
  36.         }  
  37.   
  38.         @Override  
  39.         public String toString() {  
  40.         return "SubscribeResp [nSubReqID=" + nSubReqID + ", nRespCode=" + nRespCode  
  41.             + ", strDesc=" + strDesc + "]";  
  42.         }  
  43. }  





客户端 :


SubReqClient.java

SubReqClientHand.java

SubscribeReq.java

SubscribeResp.java

和服务器一致


1            SubReqClient.java

[java] view plain copy print?
  1. package com.test.netty;  
  2.   
  3. import io.netty.bootstrap.Bootstrap;  
  4. import io.netty.channel.ChannelFuture;  
  5. import io.netty.channel.ChannelInitializer;  
  6. import io.netty.channel.ChannelOption;  
  7. import io.netty.channel.EventLoopGroup;  
  8. import io.netty.channel.nio.NioEventLoopGroup;  
  9. import io.netty.channel.socket.SocketChannel;  
  10. import io.netty.channel.socket.nio.NioSocketChannel;  
  11. import io.netty.handler.codec.serialization.ClassResolvers;  
  12. import io.netty.handler.codec.serialization.ObjectDecoder;  
  13. import io.netty.handler.codec.serialization.ObjectEncoder;  
  14.   
  15. public class SubReqClient {  
  16.   
  17.     public void connect(int nPort, String strHost) throws Exception{  
  18.         EventLoopGroup group = new NioEventLoopGroup();  
  19.         try{  
  20.             Bootstrap b = new Bootstrap();  
  21.             b.group(group).channel(NioSocketChannel.class)  
  22.             .option(ChannelOption.TCP_NODELAY,  true)  
  23.             .handler(new ChannelInitializer<SocketChannel>(){  
  24.                 @Override  
  25.                 public void initChannel(SocketChannel ch) throws Exception{  
  26.                     ch.pipeline().addLast(  
  27.                             new ObjectDecoder(1024, ClassResolvers  
  28.                                     .cacheDisabled(this.getClass().getClassLoader())));  
  29.                       
  30.                     ch.pipeline().addLast(new ObjectEncoder());  
  31.                     ch.pipeline().addLast(new SubReqClientHanler());  
  32.                 }  
  33.             });  
  34.               
  35.             ChannelFuture f = b.connect(strHost,  nPort).sync();  
  36.                           
  37. //          if(f.isSuccess()){  
  38. //              System.out.println("----------------main  get channel");      
  39. //          }else{  
  40. //              System.out.println("----------------main  get channel ---f.channel().closeFuture().sync(); END!!!!");  
  41. //          }  
  42.               
  43.             f.channel().closeFuture().sync();  
  44.               
  45. //          f.channel().closeFuture();  
  46.         }finally{  
  47.             System.out.println("----------------main  get channel Error !!! ---------");  
  48. //          group.shutdownGracefully();  
  49.         }  
  50.     }  
  51.       
  52.       
  53.     public static void main(String[] args){  
  54.         int nPort = 5656;  
  55.         String strHost = "127.0.0.1";  
  56.         try {  
  57.             System.out.println("----------------main connect");  
  58.             new SubReqClient().connect(nPort, strHost);  
  59.         } catch (Exception e) {  
  60.             System.out.println("----------------main Error");  
  61.             e.printStackTrace();  
  62.         }  
  63.     }  
  64. }  




2            SubReqClient.java

[java] view plain copy print?
  1. package com.test.netty;  
  2.   
  3.   
  4. import io.netty.channel.ChannelHandlerAdapter;  
  5. import io.netty.channel.ChannelHandlerContext;  
  6.   
  7. public class SubReqClientHanler extends ChannelHandlerAdapter{  
  8.       
  9.     public SubReqClientHanler(){  
  10.           
  11.     }  
  12.       
  13.     @Override  
  14.     public void channelActive(ChannelHandlerContext ctx){  
  15.         System.out.println("----------------handler channelActive-----准备发送十个数据-------");  
  16.           
  17.         for(int i = 0; i<10; i++){  
  18. //          ctx.write(subReq(i));  
  19.             SubscribeReq req = new SubscribeReq();  
  20.             req.setAddress("深圳蛇口");  
  21.             req.setPhoneNumber("13888886666");  
  22.             req.setProductName("Netty Book");  
  23.             req.setSubReqID(i);  
  24.             req.setUserName("XXYY");  
  25.             ctx.write(req);  
  26.         }  
  27.         ctx.flush();  
  28.     }  
  29.       
  30.     @Override  
  31.     public void channelRead(ChannelHandlerContext ctx, Object msg)  
  32.             throws Exception{  
  33.         System.out.println("--------channelRead---服务器发来的数据为:[" + msg + "]");  
  34.     }  
  35.       
  36.     @Override  
  37.     public void channelReadComplete(ChannelHandlerContext ctx)  
  38.             throws Exception{  
  39.         System.out.println("----------------handler channelReadComplete");  
  40.         ctx.flush();  
  41.     }  
  42.       
  43.       
  44.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){  
  45.         System.out.println("--------------------------------------------------------------------------handler exceptionCaught");  
  46.         cause.printStackTrace();  
  47.         ctx.close();  
  48.     }  
  49.   
  50. }  






运行结果:


服务器端:

---------------Main start
三月 30, 2016 2:47:15 下午 io.netty.handler.logging.LoggingHandler channelRegistered
信息: [id: 0x00370b13] REGISTERED
三月 30, 2016 2:47:15 下午 io.netty.handler.logging.LoggingHandler bind
信息: [id: 0x00370b13] BIND: 0.0.0.0/0.0.0.0:5656
---------------wait for connect
三月 30, 2016 2:47:15 下午 io.netty.handler.logging.LoggingHandler channelActive
信息: [id: 0x00370b13, /0:0:0:0:0:0:0:0:5656] ACTIVE
三月 30, 2016 2:47:24 下午 io.netty.handler.logging.LoggingHandler channelRead
信息: [id: 0x00370b13, /0:0:0:0:0:0:0:0:5656] RECEIVED: [id: 0x9e332f55, /127.0.0.1:56219 => /127.0.0.1:5656]
--------------------------------handler channelActive------------
接收到的数据: [  ----SubscribeReq[subReqID=0,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=1,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=2,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=3,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=4,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=5,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=6,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=7,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=8,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=9,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]



客户端:


----------------main connect
----------------handler channelActive-----准备发送十个数据-------
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
----------------handler channelReadComplete
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
----------------handler channelReadComplete



源码

http://download.csdn.NET/detail/yulinxx/9476749