mina、netty消息边界问题(采用换行符),解决半包粘包问题

在用Netty客户端返送消息时,服务端怎么也接收不到,学习发现,需要在每句消息后面加上换行符,解决消息边界问题。查阅资料如下:

一、一篇文章相关解释:

在TCP连接开始到结束连接,之间可能会多次传输数据,也就是服务器和客户端之间可能会在连接过程中互相传输多条消息。理想状况是一方每发送一条消息,另一方就立即接收到一条,也就是一次write对应一次read。但是,现实不总是按照剧本来走。

MINA官方文档节选:

TCP guarantess delivery of all packets in the correct order. But there is no guarantee that one write operation on the sender-side will result in one read event on the receiving side. One call of IoSession.write(Object message) by the sender can result in multiple messageReceived(IoSession session, Object message) events on the receiver; and multiple calls of IoSession.write(Object message) can lead to a single messageReceived event.

Netty官方文档节选:

In a stream-based transport such as TCP/IP, received data is stored into a socket receive buffer. Unfortunately, the buffer of a stream-based transport is not a queue of packets but a queue of bytes. It means, even if you sent two messages as two independent packets, an operating system will not treat them as two messages but as just a bunch of bytes. Therefore, there is no guarantee that what you read is exactly what your remote peer wrote.

上面两段话表达的意思相同:TCP是基于字节流的协议,它只能保证一方发送和另一方接收到的数据的字节顺序一致,但是,并不能保证一方每发送一条消息,另一方就能完整的接收到一条信息。有可能发送了两条对方将其合并成一条,也有可能发送了一条对方将其拆分成两条。

对此,MINA的官方文档提供了以下几种解决方案:

1、use fixed length messages

使用固定长度的消息。比如每个长度4字节,那么接收的时候按每条4字节拆分就可以了。

2、use a fixed length header that indicates the length of the body

使用固定长度的Header,Header中指定Body的长度(字节数),将信息的内容放在Body中。例如Header中指定的Body长度是100字节,那么Header之后的100字节就是Body,也就是信息的内容,100字节的Body后面就是下一条信息的Header了。

3、using a delimiter; for example many text-based protocols append a newline (or CR LF pair) after every message

使用分隔符。例如许多文本内容的协议会在每条消息后面加上换行符(CR LF,即"\r\n"),也就是一行一条消息。当然也可以用其他特殊符号作为分隔符,例如逗号、分号等等。

mina server

1

2

3

4

5

6

7

8

IoAcceptor acceptor = new NioSocketAcceptor(); 

        

     // 添加一个Filter,用于接收、发送的内容按照"\r\n"分割 

     acceptor.getFilterChain().addLast("codec",  

             new ProtocolCodecFilter((ProtocolCodecFactory) new TextLineCodecFactory(Charset.forName("UTF-8"), "\r\n""\r\n"))); 

      

     acceptor.setHandler((IoHandler) new TcpServerHandle2()); 

     acceptor.bind(new InetSocketAddress(8080));

netty server

几种方式对应的实现类:

1、消息长度固定,累计读取到消息长度总和为定长Len的报文之后即认为是读取到了一个完整的消息。计数器归位,重新读取。

FixedLengthFrameDecoder
2、将回车换行符作为消息结束符。 采用LineBasedframeDecoder
3、将特殊的分隔符作为消息分隔符,回车换行符是他的一种。 DelimiterBasedFrameDecoder

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

ServerBootstrap b = new ServerBootstrap(); 

  b.group(bossGroup, workerGroup) 

  .channel(NioServerSocketChannel.class

  .childHandler(new ChannelInitializer() { 

       @Override       

       public void initChannel(SocketChannel ch)throws Exception { 

         ChannelPipeline pipeline = ch.pipeline(); 

//固定长度

//pipeline.addLast(new FixedLengthFrameDecoder(64));         

            // LineBasedFrameDecoder按行分割消息 

         pipeline.addLast(new LineBasedFrameDecoder(80)); 

//  自行定义分隔符

//pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

         // 再按UTF-8编码转成字符串 

         pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));                       

         pipeline.addLast(new TcpServerHandler2()); 

       } 

   }); 

ChannelFuture f = b.bind(8080).sync(); 

f.channel().closeFuture().sync();

   

你可能感兴趣的:(Netty)