一起学Netty(六)之 TCP粘包拆包场景

TCP编程底层都有粘包和拆包机制,因为我们在C/S这种传输模型下,以TCP协议传输的时候,在网络中的byte其实就像是河水,TCP就像一个搬运工,将这流水从一端转送到另一端,这时又分两种情况:

1)如果客户端的每次制造的水比较多,也就是我们常说的客户端给的包比较大,TCP这个搬运工就会分多次去搬运。

2)如果客户端每次制造的水比较少的话,TCP可能会等客户端多次生产之后,把所有的水一起再运输到另一端


上述第一种情况,就是需要我们进行粘包,在另一端接收的时候,需要把多次获取的结果粘在一起,变成我们可以理解的信息,第二种情况,我们在另一端接收的时候,就必须进行拆包处理,因为每次接收的信息,可能是另一个远程端多次发送的包,被TCP粘在一起的


我们进行上述两种情况给出具体的场景:

1)单次发送的包内容过多的情况,拆包的现象:

我们先写客户端的bootstrap:

[java]  view plain  copy
  1. package com.lyncc.netty.stickpackage.myself;  
  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.ChannelPipeline;  
  8. import io.netty.channel.EventLoopGroup;  
  9. import io.netty.channel.nio.NioEventLoopGroup;  
  10. import io.netty.channel.socket.SocketChannel;  
  11. import io.netty.channel.socket.nio.NioSocketChannel;  
  12. import io.netty.handler.codec.LineBasedFrameDecoder;  
  13. import io.netty.handler.codec.string.StringDecoder;  
  14.   
  15. public class BaseClient {  
  16.       
  17.     static final String HOST = System.getProperty("host""127.0.0.1");  
  18.     static final int PORT = Integer.parseInt(System.getProperty("port""8080"));  
  19.     static final int SIZE = Integer.parseInt(System.getProperty("size""256"));  
  20.   
  21.     public static void main(String[] args) throws Exception {  
  22.   
  23.         EventLoopGroup group = new NioEventLoopGroup();  
  24.         try {  
  25.             Bootstrap b = new Bootstrap();  
  26.             b.group(group)  
  27.              .channel(NioSocketChannel.class)  
  28.              .option(ChannelOption.TCP_NODELAY,true)  
  29.              .handler(new ChannelInitializer<SocketChannel>() {  
  30.                  @Override  
  31.                  public void initChannel(SocketChannel ch) throws Exception {  
  32.                      ChannelPipeline p = ch.pipeline();  
  33. //                     p.addLast(new LineBasedFrameDecoder(1024));  
  34.                      p.addLast(new StringDecoder());  
  35.                      p.addLast(new BaseClientHandler());  
  36.                  }  
  37.              });  
  38.   
  39.             ChannelFuture future = b.connect(HOST, PORT).sync();  
  40.             future.channel().writeAndFlush("Hello Netty Server ,I am a common client");  
  41.             future.channel().closeFuture().sync();  
  42.         } finally {  
  43.             group.shutdownGracefully();  
  44.         }  
  45.     }  
  46.   
  47. }  
客户端的handler:

[java]  view plain  copy
  1. package com.lyncc.netty.stickpackage.myself;  
  2.   
  3. import io.netty.buffer.ByteBuf;  
  4. import io.netty.buffer.Unpooled;  
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.ChannelInboundHandlerAdapter;  
  7.   
  8. public class BaseClientHandler extends ChannelInboundHandlerAdapter{  
  9.       
  10.     private byte[] req;  
  11.       
  12.     private int counter;  
  13.       
  14.     public BaseClientHandler() {  
  15. //        req = ("BazingaLyncc is learner" + System.getProperty("line.separator"))  
  16. //            .getBytes();  
  17.         req = ("In this chapter you general, we recommend Java Concurrency in Practice by Brian Goetz. His book w"  
  18.                 + "ill give We’ve reached an exciting point—in the next chapter we’ll discuss bootstrapping, the process "  
  19.                 + "of configuring and connecting all of Netty’s components to bring your learned about threading models in ge"  
  20.                 + "neral and Netty’s threading model in particular, whose performance and consistency advantages we discuss"  
  21.                 + "ed in detail In this chapter you general, we recommend Java Concurrency in Practice by Brian Goetz. Hi"  
  22.                 + "s book will give We’ve reached an exciting point—in the next chapter we’ll discuss bootstrapping, the"  
  23.                 + " process of configuring and connecting all of Netty’s components to bring your learned about threading "  
  24.                 + "models in general and Netty’s threading model in particular, whose performance and consistency advantag"  
  25.                 + "es we discussed in detailIn this chapter you general, we recommend Java Concurrency in Practice by Bri"  
  26.                 + "an Goetz. His book will give We’ve reached an exciting point—in the next chapter;the counter is: 1 2222"  
  27.                 + "sdsa ddasd asdsadas dsadasdas").getBytes();  
  28.     }  
  29.       
  30.     @Override  
  31.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  32.         ByteBuf message = null;  
  33. //        for (int i = 0; i < 100; i++) {  
  34. //            message = Unpooled.buffer(req.length);  
  35. //            message.writeBytes(req);  
  36. //            ctx.writeAndFlush(message);  
  37. //        }  
  38.         message = Unpooled.buffer(req.length);  
  39.         message.writeBytes(req);  
  40.         ctx.writeAndFlush(message);  
  41.         message = Unpooled.buffer(req.length);  
  42.         message.writeBytes(req);  
  43.         ctx.writeAndFlush(message);  
  44.     }  
  45.       
  46.     @Override  
  47.     public void channelRead(ChannelHandlerContext ctx, Object msg)  
  48.         throws Exception {  
  49.         String buf = (String) msg;  
  50.         System.out.println("Now is : " + buf + " ; the counter is : "+ ++counter);  
  51.     }  
  52.   
  53.     @Override  
  54.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {  
  55.         ctx.close();  
  56.     }  
  57.       
  58.       
  59.   
  60. }  
服务端的serverBootstrap:

[java]  view plain  copy
  1. package com.lyncc.netty.stickpackage.myself;  
  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.string.StringDecoder;  
  12.   
  13. import java.net.InetSocketAddress;  
  14.   
  15. public class BaseServer {  
  16.   
  17.     private int port;  
  18.       
  19.     public BaseServer(int port) {  
  20.         this.port = port;  
  21.     }  
  22.       
  23.     public void start(){  
  24.         EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
  25.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  26.         try {  
  27.             ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))  
  28.                     .childHandler(new ChannelInitializer<SocketChannel>() {  
  29.                           
  30.                         protected void initChannel(SocketChannel ch) throws Exception {  
  31. //                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));  
  32.                             ch.pipeline().addLast(new StringDecoder());  
  33.                             ch.pipeline().addLast(new BaseServerHandler());  
  34.                         };  
  35.                           
  36.                     }).option(ChannelOption.SO_BACKLOG, 128)     
  37.                     .childOption(ChannelOption.SO_KEEPALIVE, true);  
  38.              // 绑定端口,开始接收进来的连接  
  39.              ChannelFuture future = sbs.bind(port).sync();    
  40.                
  41.              System.out.println("Server start listen at " + port );  
  42.              future.channel().closeFuture().sync();  
  43.         } catch (Exception e) {  
  44.             bossGroup.shutdownGracefully();  
  45.             workerGroup.shutdownGracefully();  
  46.         }  
  47.     }  
  48.       
  49.     public static void main(String[] args) throws Exception {  
  50.         int port;  
  51.         if (args.length > 0) {  
  52.             port = Integer.parseInt(args[0]);  
  53.         } else {  
  54.             port = 8080;  
  55.         }  
  56.         new BaseServer(port).start();  
  57.     }  
  58. }  
服务端的handler:

[java]  view plain  copy
  1. package com.lyncc.netty.stickpackage.myself;  
  2.   
  3. import io.netty.channel.ChannelHandlerContext;  
  4. import io.netty.channel.ChannelInboundHandlerAdapter;  
  5.   
  6. public class BaseServerHandler extends ChannelInboundHandlerAdapter{  
  7.       
  8.       
  9.     private int counter;  
  10.       
  11.       
  12.     @Override  
  13.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
  14.           
  15.         String body = (String)msg;  
  16.         System.out.println("server receive order : " + body + ";the counter is: " + ++counter);  
  17.     }  
  18.       
  19.       
  20.     @Override  
  21.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
  22.         cause.printStackTrace();  
  23.         ctx.close();  
  24.     }  
  25.   
  26. }  

照例,我们先运行服务器端:

我们再运行客户端,客户端启动后,我们再看看服务器端的控制台打印输出:

我们可以看到服务器端分三次接收到了客户端两次发送的那段很长的信息


2)单次发送的包内容过多的情况,粘包的现象:

客户端和服务端的bootstrap不改变,我们修改一下,客户端发送信息的channelActive的代码:

[java]  view plain  copy
  1. package com.lyncc.netty.stickpackage.myself;  
  2.   
  3. import io.netty.buffer.ByteBuf;  
  4. import io.netty.buffer.Unpooled;  
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.ChannelInboundHandlerAdapter;  
  7.   
  8. public class BaseClientHandler extends ChannelInboundHandlerAdapter{  
  9.       
  10.     private byte[] req;  
  11.       
  12.     private int counter;  
  13.       
  14.     public BaseClientHandler() {  
  15.         req = ("BazingaLyncc is learner").getBytes();  
  16. //        req = ("In this chapter you general, we recommend Java Concurrency in Practice by Brian Goetz. His book w"  
  17. //                + "ill give We’ve reached an exciting point—in the next chapter we’ll discuss bootstrapping, the process "  
  18. //                + "of configuring and connecting all of Netty’s components to bring your learned about threading models in ge"  
  19. //                + "neral and Netty’s threading model in particular, whose performance and consistency advantages we discuss"  
  20. //                + "ed in detail In this chapter you general, we recommend Java Concurrency in Practice by Brian Goetz. Hi"  
  21. //                + "s book will give We’ve reached an exciting point—in the next chapter we’ll discuss bootstrapping, the"  
  22. //                + " process of configuring and connecting all of Netty’s components to bring your learned about threading "  
  23. //                + "models in general and Netty’s threading model in particular, whose performance and consistency advantag"  
  24. //                + "es we discussed in detailIn this chapter you general, we recommend Java Concurrency in Practice by Bri"  
  25. //                + "an Goetz. His book will give We’ve reached an exciting point—in the next chapter;the counter is: 1 2222"  
  26. //                + "sdsa ddasd asdsadas dsadasdas").getBytes();  
  27.     }  
  28.       
  29.     @Override  
  30.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  31.         ByteBuf message = null;  
  32.         for (int i = 0; i < 100; i++) {  
  33.             message = Unpooled.buffer(req.length);  
  34.             message.writeBytes(req);  
  35.             ctx.writeAndFlush(message);  
  36.         }  
  37. //        message = Unpooled.buffer(req.length);  
  38. //        message.writeBytes(req);  
  39. //        ctx.writeAndFlush(message);  
  40. //        message = Unpooled.buffer(req.length);  
  41. //        message.writeBytes(req);  
  42. //        ctx.writeAndFlush(message);  
  43.     }  
  44.   
  45.     @Override  
  46.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {  
  47.         ctx.close();  
  48.     }  
  49.   
  50. }  
我们再次启动服务器端:


启动客户端后,依旧看服务器端的控制台:

可以看出,客户端发送100次的信息,被服务器端分三次就接收了,这就发生了粘包的现象


以上就是典型的粘包和拆包的场景


   2.4 粘包问题的解决办法

粘包的解决办法有很多,可以归纳如下。

  • 消息定长,例如每个报文的大小为固定长度200字节,如果不够,空位补空格。
  • 在包尾增加回车换行符进行分割,例如FTP协议。
  • 将消息分为消息头和消息体,消息头中包含消息长度的字段,通常设计思路为消息头的第一个字段使用int32来表示消息的总长度

在本案例中,我使用的是第2个解决办法在包尾增加回车换行符进行分割。


自定义协议实现

1、什么是粘包/拆包

       一般所谓的TCP粘包是在一次接收数据不能完全地体现一个完整的消息数据。TCP通讯为何存在粘包呢?主要原因是TCP是以流的方式来处理数据,再加上网络上MTU的往往小于在应用处理的消息数据,所以就会引发一次接收的数据无法满足消息的需要,导致粘包的存在。处理粘包的唯一方法就是制定应用层的数据通讯协议,通过协议来规范现有接收的数据是否满足消息数据的需要。

2、解决办法

     2.1、消息定长,报文大小固定长度,不够空格补全,发送和接收方遵循相同的约定,这样即使粘包了通过接收方编程实现获取定长报文也能区分。

     2.2、包尾添加特殊分隔符,例如每条报文结束都添加回车换行符(例如FTP协议)或者指定特殊字符作为报文分隔符,接收方通过特殊分隔符切分报文区分。

     2.3、将消息分为消息头和消息体,消息头中包含表示信息的总长度(或者消息体长度)的字段

3、自定义协议,来实现TCP的粘包/拆包问题

      3.0  自定义协议,开始标记           

              

      3.1  自定义协议的介绍

             

      3.2  自定义协议的类的封装

             

      3.3  自定义协议的编码器

             

      3.4  自定义协议的解码器

          

4、协议相关的实现

      4.1  协议的封装

 

[java]  view plain  copy
 
 print?
  1. import java.util.Arrays;  
  2.   
  3. /** 
  4.  * <pre> 
  5.  * 自己定义的协议 
  6.  *  数据包格式 
  7.  * +——----——+——-----——+——----——+ 
  8.  * |协议开始标志|  长度             |   数据       | 
  9.  * +——----——+——-----——+——----——+ 
  10.  * 1.协议开始标志head_data,为int类型的数据,16进制表示为0X76 
  11.  * 2.传输数据的长度contentLength,int类型 
  12.  * 3.要传输的数据 
  13.  * </pre> 
  14.  */  
  15. public class SmartCarProtocol {  
  16.     /** 
  17.      * 消息的开头的信息标志 
  18.      */  
  19.     private int head_data = ConstantValue.HEAD_DATA;  
  20.     /** 
  21.      * 消息的长度 
  22.      */  
  23.     private int contentLength;  
  24.     /** 
  25.      * 消息的内容 
  26.      */  
  27.     private byte[] content;  
  28.   
  29.     /** 
  30.      * 用于初始化,SmartCarProtocol 
  31.      *  
  32.      * @param contentLength 
  33.      *            协议里面,消息数据的长度 
  34.      * @param content 
  35.      *            协议里面,消息的数据 
  36.      */  
  37.     public SmartCarProtocol(int contentLength, byte[] content) {  
  38.         this.contentLength = contentLength;  
  39.         this.content = content;  
  40.     }  
  41.   
  42.     public int getHead_data() {  
  43.         return head_data;  
  44.     }  
  45.   
  46.     public int getContentLength() {  
  47.         return contentLength;  
  48.     }  
  49.   
  50.     public void setContentLength(int contentLength) {  
  51.         this.contentLength = contentLength;  
  52.     }  
  53.   
  54.     public byte[] getContent() {  
  55.         return content;  
  56.     }  
  57.   
  58.     public void setContent(byte[] content) {  
  59.         this.content = content;  
  60.     }  
  61.   
  62.     @Override  
  63.     public String toString() {  
  64.         return "SmartCarProtocol [head_data=" + head_data + ", contentLength="  
  65.                 + contentLength + ", content=" + Arrays.toString(content) + "]";  
  66.     }  
  67.   
  68. }  

 

      4.2  协议的编码器

 

[java]  view plain  copy
 
 print?
  1. /** 
  2.  * <pre> 
  3.  * 自己定义的协议 
  4.  *  数据包格式 
  5.  * +——----——+——-----——+——----——+ 
  6.  * |协议开始标志|  长度             |   数据       | 
  7.  * +——----——+——-----——+——----——+ 
  8.  * 1.协议开始标志head_data,为int类型的数据,16进制表示为0X76 
  9.  * 2.传输数据的长度contentLength,int类型 
  10.  * 3.要传输的数据 
  11.  * </pre> 
  12.  */  
  13. public class SmartCarEncoder extends MessageToByteEncoder<SmartCarProtocol> {  
  14.   
  15.     @Override  
  16.     protected void encode(ChannelHandlerContext tcx, SmartCarProtocol msg,  
  17.             ByteBuf out) throws Exception {  
  18.         // 写入消息SmartCar的具体内容  
  19.         // 1.写入消息的开头的信息标志(int类型)  
  20.         out.writeInt(msg.getHead_data());  
  21.         // 2.写入消息的长度(int 类型)  
  22.         out.writeInt(msg.getContentLength());  
  23.         // 3.写入消息的内容(byte[]类型)  
  24.         out.writeBytes(msg.getContent());  
  25.     }  
  26. }  

 

      4.3  协议的解码器

 

[java]  view plain  copy
 
 print?
  1. import java.util.List;  
  2. import io.netty.buffer.ByteBuf;  
  3. import io.netty.channel.ChannelHandlerContext;  
  4. import io.netty.handler.codec.ByteToMessageDecoder;  
  5.   
  6. /** 
  7.  * <pre> 
  8.  * 自己定义的协议 
  9.  *  数据包格式 
  10.  * +——----——+——-----——+——----——+ 
  11.  * |协议开始标志|  长度             |   数据       | 
  12.  * +——----——+——-----——+——----——+ 
  13.  * 1.协议开始标志head_data,为int类型的数据,16进制表示为0X76 
  14.  * 2.传输数据的长度contentLength,int类型 
  15.  * 3.要传输的数据,长度不应该超过2048,防止socket流的攻击 
  16.  * </pre> 
  17.  */  
  18. public class SmartCarDecoder extends ByteToMessageDecoder {  
  19.   
  20.     /** 
  21.      * <pre> 
  22.      * 协议开始的标准head_data,int类型,占据4个字节. 
  23.      * 表示数据的长度contentLength,int类型,占据4个字节. 
  24.      * </pre> 
  25.      */  
  26.     public final int BASE_LENGTH = 4 + 4;  
  27.   
  28.     @Override  
  29.     protected void decode(ChannelHandlerContext ctx, ByteBuf buffer,  
  30.             List<Object> out) throws Exception {  
  31.         // 可读长度必须大于基本长度  
  32.         if (buffer.readableBytes() >= BASE_LENGTH) {  
  33.             // 防止socket字节流攻击  
  34.             // 防止,客户端传来的数据过大  
  35.             // 因为,太大的数据,是不合理的  
  36.             if (buffer.readableBytes() > 2048) {  
  37.                 buffer.skipBytes(buffer.readableBytes());  
  38.             }  
  39.   
  40.             // 记录包头开始的index  
  41.             int beginReader;  
  42.   
  43.             while (true) {  
  44.                 // 获取包头开始的index  
  45.                 beginReader = buffer.readerIndex();  
  46.                 // 标记包头开始的index  
  47.                 buffer.markReaderIndex();  
  48.                 // 读到了协议的开始标志,结束while循环  
  49.                 if (buffer.readInt() == ConstantValue.HEAD_DATA) {  
  50.                     break;  
  51.                 }  
  52.   
  53.                 // 未读到包头,略过一个字节  
  54.                 // 每次略过,一个字节,去读取,包头信息的开始标记  
  55.                 buffer.resetReaderIndex();  
  56.                 buffer.readByte();  
  57.   
  58.                 // 当略过,一个字节之后,  
  59.                 // 数据包的长度,又变得不满足  
  60.                 // 此时,应该结束。等待后面的数据到达  
  61.                 if (buffer.readableBytes() < BASE_LENGTH) {  
  62.                     return;  
  63.                 }  
  64.             }  
  65.   
  66.             // 消息的长度  
  67.   
  68.             int length = buffer.readInt();  
  69.             // 判断请求数据包数据是否到齐  
  70.             if (buffer.readableBytes() < length) {  
  71.                 // 还原读指针  
  72.                 buffer.readerIndex(beginReader);  
  73.                 return;  
  74.             }  
  75.   
  76.             // 读取data数据  
  77.             byte[] data = new byte[length];  
  78.             buffer.readBytes(data);  
  79.   
  80.             SmartCarProtocol protocol = new SmartCarProtocol(data.length, data);  
  81.             out.add(protocol);  
  82.         }  
  83.     }  
  84.   
  85. }  

 

      4.4  服务端加入协议的编/解码器

            

      4.5  客户端加入协议的编/解码器

          

5、服务端的实现

 

[java]  view plain  copy
 
 print?
  1. import io.netty.bootstrap.ServerBootstrap;  
  2. import io.netty.channel.ChannelFuture;  
  3. import io.netty.channel.ChannelInitializer;  
  4. import io.netty.channel.ChannelOption;  
  5. import io.netty.channel.EventLoopGroup;  
  6. import io.netty.channel.nio.NioEventLoopGroup;  
  7. import io.netty.channel.socket.SocketChannel;  
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  9. import io.netty.handler.logging.LogLevel;  
  10. import io.netty.handler.logging.LoggingHandler;  
  11.   
  12. public class Server {  
  13.   
  14.     public Server() {  
  15.     }  
  16.   
  17.     public void bind(int port) throws Exception {  
  18.         // 配置NIO线程组  
  19.         EventLoopGroup bossGroup = new NioEventLoopGroup();  
  20.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  21.         try {  
  22.             // 服务器辅助启动类配置  
  23.             ServerBootstrap b = new ServerBootstrap();  
  24.             b.group(bossGroup, workerGroup)  
  25.                     .channel(NioServerSocketChannel.class)  
  26.                     .handler(new LoggingHandler(LogLevel.INFO))  
  27.                     .childHandler(new ChildChannelHandler())//  
  28.                     .option(ChannelOption.SO_BACKLOG, 1024) // 设置tcp缓冲区 // (5)  
  29.                     .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)  
  30.             // 绑定端口 同步等待绑定成功  
  31.             ChannelFuture f = b.bind(port).sync(); // (7)  
  32.             // 等到服务端监听端口关闭  
  33.             f.channel().closeFuture().sync();  
  34.         } finally {  
  35.             // 优雅释放线程资源  
  36.             workerGroup.shutdownGracefully();  
  37.             bossGroup.shutdownGracefully();  
  38.         }  
  39.     }  
  40.   
  41.     /** 
  42.      * 网络事件处理器 
  43.      */  
  44.     private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {  
  45.         @Override  
  46.         protected void initChannel(SocketChannel ch) throws Exception {  
  47.             // 添加自定义协议的编解码工具  
  48.             ch.pipeline().addLast(new SmartCarEncoder());  
  49.             ch.pipeline().addLast(new SmartCarDecoder());  
  50.             // 处理网络IO  
  51.             ch.pipeline().addLast(new ServerHandler());  
  52.         }  
  53.     }  
  54.   
  55.     public static void main(String[] args) throws Exception {  
  56.         new Server().bind(9999);  
  57.     }  
  58. }  

6、服务端Handler的实现

 

 

[java]  view plain  copy
 
 print?
  1. import io.netty.channel.ChannelHandlerAdapter;  
  2. import io.netty.channel.ChannelHandlerContext;  
  3.   
  4. public class ServerHandler extends ChannelHandlerAdapter {  
  5.     // 用于获取客户端发送的信息  
  6.     @Override  
  7.     public void channelRead(ChannelHandlerContext ctx, Object msg)  
  8.             throws Exception {  
  9.         // 用于获取客户端发来的数据信息  
  10.         SmartCarProtocol body = (SmartCarProtocol) msg;  
  11.         System.out.println("Server接受的客户端的信息 :" + body.toString());  
  12.   
  13.         // 会写数据给客户端  
  14.         String str = "Hi I am Server ...";  
  15.         SmartCarProtocol response = new SmartCarProtocol(str.getBytes().length,  
  16.                 str.getBytes());  
  17.         // 当服务端完成写操作后,关闭与客户端的连接  
  18.         ctx.writeAndFlush(response);  
  19.         // .addListener(ChannelFutureListener.CLOSE);  
  20.   
  21.         // 当有写操作时,不需要手动释放msg的引用  
  22.         // 当只有读操作时,才需要手动释放msg的引用  
  23.     }  
  24.   
  25.     @Override  
  26.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  
  27.             throws Exception {  
  28.         // cause.printStackTrace();  
  29.         ctx.close();  
  30.     }  
  31. }  

7、客户端的实现

 

 

[java]  view plain  copy
 
 print?
  1. import io.netty.bootstrap.Bootstrap;  
  2. import io.netty.channel.ChannelFuture;  
  3. import io.netty.channel.ChannelInitializer;  
  4. import io.netty.channel.ChannelOption;  
  5. import io.netty.channel.EventLoopGroup;  
  6. import io.netty.channel.nio.NioEventLoopGroup;  
  7. import io.netty.channel.socket.SocketChannel;  
  8. import io.netty.channel.socket.nio.NioSocketChannel;  
  9.   
  10. public class Client {  
  11.   
  12.     /** 
  13.      * 连接服务器 
  14.      *  
  15.      * @param port 
  16.      * @param host 
  17.      * @throws Exception 
  18.      */  
  19.     public void connect(int port, String host) throws Exception {  
  20.         // 配置客户端NIO线程组  
  21.         EventLoopGroup group = new NioEventLoopGroup();  
  22.         try {  
  23.             // 客户端辅助启动类 对客户端配置  
  24.             Bootstrap b = new Bootstrap();  
  25.             b.group(group)//  
  26.                     .channel(NioSocketChannel.class)//  
  27.                     .option(ChannelOption.TCP_NODELAY, true)//  
  28.                     .handler(new MyChannelHandler());//  
  29.             // 异步链接服务器 同步等待链接成功  
  30.             ChannelFuture f = b.connect(host, port).sync();  
  31.   
  32.             // 等待链接关闭  
  33.             f.channel().closeFuture().sync();  
  34.   
  35.         } finally {  
  36.             group.shutdownGracefully();  
  37.             System.out.println("客户端优雅的释放了线程资源...");  
  38.         }  
  39.   
  40.     }  
  41.   
  42.     /** 
  43.      * 网络事件处理器 
  44.      */  
  45.     private class MyChannelHandler extends ChannelInitializer<SocketChannel> {  
  46.         @Override  
  47.         protected void initChannel(SocketChannel ch) throws Exception {  
  48.             // 添加自定义协议的编解码工具  
  49.             ch.pipeline().addLast(new SmartCarEncoder());  
  50.             ch.pipeline().addLast(new SmartCarDecoder());  
  51.             // 处理网络IO  
  52.             ch.pipeline().addLast(new ClientHandler());  
  53.         }  
  54.   
  55.     }  
  56.   
  57.     public static void main(String[] args) throws Exception {  
  58.         new Client().connect(9999, "127.0.0.1");  
  59.   
  60.     }  
  61.   
  62. }  

8、客户端Handler的实现

 

 

[java]  view plain  copy
 
 print?
  1. import io.netty.channel.ChannelHandlerAdapter;  
  2. import io.netty.channel.ChannelHandlerContext;  
  3. import io.netty.util.ReferenceCountUtil;  
  4.   
  5. //用于读取客户端发来的信息  
  6. public class ClientHandler extends ChannelHandlerAdapter {  
  7.   
  8.     // 客户端与服务端,连接成功的售后  
  9.     @Override  
  10.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  11.         // 发送SmartCar协议的消息  
  12.         // 要发送的信息  
  13.         String data = "I am client ...";  
  14.         // 获得要发送信息的字节数组  
  15.         byte[] content = data.getBytes();  
  16.         // 要发送信息的长度  
  17.         int contentLength = content.length;  
  18.   
  19.         SmartCarProtocol protocol = new SmartCarProtocol(contentLength, content);  
  20.   
  21.         ctx.writeAndFlush(protocol);  
  22.     }  
  23.   
  24.     // 只是读数据,没有写数据的话  
  25.     // 需要自己手动的释放的消息  
  26.     @Override  
  27.     public void channelRead(ChannelHandlerContext ctx, Object msg)  
  28.             throws Exception {  
  29.         try {  
  30.             // 用于获取客户端发来的数据信息  
  31.             SmartCarProtocol body = (SmartCarProtocol) msg;  
  32.             System.out.println("Client接受的客户端的信息 :" + body.toString());  
  33.   
  34.         } finally {  
  35.             ReferenceCountUtil.release(msg);  
  36.         }  
  37.     }  
  38.   
  39.     @Override  
  40.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  
  41.             throws Exception {  
  42.         ctx.close();  
  43.     }  
  44.   
  45. }  


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值