TCP以流的方式進行資料傳輸,上層的應用協定為了對消息進行區分,往往采用如下4種方式
消息長度固定,累計讀取到長度總和為定長的LEN的封包後,就認為讀取到了一個完整的消息,将計數器置位,重新開始讀取下一個資料報。
将回車換行符作為消息的結束标志,例如FTP協定,這種方式在文本協定中應用比較廣泛;
将特殊的分隔符作為消息的結束标志,回車換行符就是一種特殊的結束分隔符
通過在消息頭中定義長度字段來标志消息的總長度。
Netty對上面4中應用做了統一的抽象,提供了4中解碼器來解決對應的問題,使用起來非常友善,有了這些解碼器,使用者不需要自己對讀取的封包進行人工解碼,也不需要考慮TCP的粘包和拆包。
DelimiterBasedFrameDecoder
DelimiterBasedFrameDecoder可以幫助我們自動完成以分隔符作為碼流結束标示的消息的解碼。通過案例我們具體來看下,案例中以"$_"作為分隔符
服務端
EchoServer
package com.dpb.netty.demo3;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* DelimiterBasedFrameDecoder案例
* 服務端
* @author 波波烤鴨
* @email [email protected]
*
*/
public class EchoServer {
public void bind(int port) throws Exception {
// 配置服務端的NIO線程組
// 服務端接受用戶端的連接配接
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// 進行SocketChannel的網絡讀寫
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 1.定義分隔符
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
// 2.添加分隔符解碼器 單條消息最大長度1024,
// 當到達長度後仍然沒有查找到分隔符,就抛TooLongFrameException
// 第二個參數是分隔符緩沖對象
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
// 3.添加字元串處了解碼器
ch.pipeline().addLast(new StringDecoder());
// 4.添加自定義的處理器
ch.pipeline().addLast(new EchoServerHandler());
}
});
// 綁定端口,同步等待成功
ChannelFuture f = b.bind(port).sync();
// 等待服務端監聽端口關閉
f.channel().closeFuture().sync();
} finally {
// 優雅退出,釋放線程池資源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if(args!=null && args.length > 0){
try{
port = Integer.valueOf(args[0]);
}catch(NumberFormatException e){
// 采用預設值
}
}
new EchoServer().bind(port);
}
}
EchoServerHandler
package com.dpb.netty.demo3;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* DelimiterBasedFrameDecoder 案例
* 自定義處理器
* @author 波波烤鴨
* @email [email protected]
*
*/
public class EchoServerHandler extends ChannelHandlerAdapter{
// 統計接收消息的數量
private int counter;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 擷取用戶端傳遞的消息
String body = (String) msg;
// 列印消息
System.out.println("This is "+ ++counter + " times receive client :["+body+"]");
// 分隔符已經被截取掉了,響應資訊的時候我們需要再加上分隔符
body += "$_";
ByteBuf echo = Unpooled.copiedBuffer(body.getBytes());
ctx.writeAndFlush(echo);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close(); // 發生異常關閉鍊路
}
}
客戶斷
EchoClient
package com.dpb.netty.demo3;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
/**
* DelimiterBasedFrameDecoder 案例 用戶端
*
* @author 波波烤鴨
* @email [email protected]
*
*/
public class EchoClient {
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
// 采用預設值
}
}
new EchoClient().connector(port, "127.0.0.1");
}
public void connector(int port, String host) throws Exception {
// 配置用戶端NIO線程組
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// TODO Auto-generated method stub
// 1.定義分隔符
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
// 2.添加分隔符解碼器
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
// 3.添加字元串處了解碼器
ch.pipeline().addLast(new StringDecoder());
// 4.添加自定義的處理器
ch.pipeline().addLast(new EchoClientHandler());
}
});
// 發起異步連接配接操作
ChannelFuture f = b.connect(host, port).sync();
// 等待用戶端鍊路關閉
f.channel().closeFuture().sync();
} finally {
// 優雅退出,釋放NIO線程組
group.shutdownGracefully();
}
}
}
EchoClientHandler
package com.dpb.netty.demo3;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* DelimiterBasedFrameDecoder 案例
* 自定義用戶端處理器
* @author 波波烤鴨
* @email [email protected]
*
*/
public class EchoClientHandler extends ChannelHandlerAdapter{
private int counter;
static final String ECHO_REQ = "Hi , bobo烤鴨. Welcome to Netty.$_";
public EchoClientHandler(){
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
// 發送消息别立馬重新整理
ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
System.out.println("This is "+ ++counter + "time recevice server :【"+msg+"】");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
cause.printStackTrace();
ctx.close();
}
}
測試
服務端運作結果
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5CZmBjNhNTNmJTNkFTNkBTO3YDZ0AzNwMTNyUjZhlDZ38CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
用戶端運作結果
服務端成功接收到了用戶端發送的10條資訊,用戶端成功接收到了服務端傳回的10條資訊,測試結果表明使用DelimiterBasedFrameDecoder可以自動對采用分隔符做碼流結束辨別的消息進行解碼。運作多次的原因是模拟TCP粘包/拆包,如果沒有DelimiterBasedFrameDecoder解碼處理,服務端和用戶端都将運作失敗,如下:
輸出結果:
This is 1 times receive client :
[Hi , bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_Hi ,
bobo烤鴨. Welcome to Netty.$_]
用戶端發送的10條資訊,在服務端粘包成一條資訊了。那麼響應資訊肯定也是一條了。
FixedLengthFrameDecoder
FixedLengthFrameDecoder是固定長度解碼器,它能夠按照指定的長度對消息進行自動解碼,開發者不需要考慮TCP的粘包/拆包問題,非常使用。通過案例來示範。
服務端還是用上個案例中的代碼,我們需要調整兩處地方
用戶端
用戶端不用處理,就用上面案例中的就可以,服務端不傳回響應,是以用戶端也不用處理響應的資料。直接運作用戶端
總結
DelimiterBasedFrameDecoder用于對使用分隔符結尾的資訊進行自動解碼,FixedLengthFrameDecoder用于對固定長度的消息進行自動解碼,有了上述兩種解碼器再結合其他的解碼器,如字元串解碼器等,可以輕松地完成對很多消息自動解碼,而且不再需要考慮TCP粘包/拆包導緻的讀半包問題,極大地提升了開發效率。