业务上一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。
对于这类问题,netty提供了LineBasedFrameDecoder和StringDecoder进行完美解决。如下是相关代码。
代码
- TimeServer
package com.xpn.netty.netty;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
public class TimeServer {
public void bind(int port) throws InterruptedException {
// 配置NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();// 连接线程
EventLoopGroup workerGroup = new NioEventLoopGroup();// 处理线程组
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.childHandler(new ChildChannelHandler());
// 绑定端口,同步等待成功
ChannelFuture future = bootstrap.bind(port).sync();
// 等待服务端监听端口关闭,等待服务端链路关闭之后main函数才退出
future.channel().closeFuture().sync();
} finally {
// 优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//半包解决
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new TimeServerHandler());
}
}
public static void main(String[] args) throws InterruptedException {
int port = 8080;
if (args != null && args.length > 0) {
port = Integer.parseInt(args[0]);
}
new TimeServer().bind(port);
}
}
- TimeClient
package com.xpn.netty.netty;
import io.netty.bootstrap.Bootstrap;
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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
public class TimeClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String host = "localhost";
int port = 8080;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//先后顺序。
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new TimeClientHandler());
}
});
// 发起异步连接操作
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
} catch (Exception e) {
workerGroup.shutdownGracefully();
}
}
}
- TimeServerHandler
package com.xpn.netty.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.Date;
public class TimeServerHandler extends ChannelHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
// TODO Auto-generated method stub
cause.printStackTrace();
ctx.close();
}
private int counter;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
/*ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];// 获得缓冲区可读的字节数
buf.readBytes(req);
//String body = new String(req, "UTF-8");
String body = new String(req, "UTF-8").substring(0,req.length
-System.getProperty("line.separator").length());//
*/ String body=(String)msg;
System.out.println("the time server receive order : " + body
+ " ;the counter is "+ ++counter);
String currentTime = "query time order".equalsIgnoreCase(body) ? new Date(
System.currentTimeMillis()).toString() : "bad order";
currentTime+=System.getProperty("line.separator");
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);// 性能考虑,仅将待发送的消息发送到缓冲数组中,再通过调用flush方法,写入channel中
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();// 将消息发送队列中的消息写入到SocketChannel中发送给对方。
}
}
- TimeClientHandler
package com.xpn.netty.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.logging.Logger;
public class TimeClientHandler extends ChannelHandlerAdapter {
private static final Logger LOGGER = Logger
.getLogger(TimeClientHandler.class.getName());
private final ByteBuf firstMessage;
private byte[] req;
private int counter;
public TimeClientHandler() {
req = ("query time order"+System.getProperty("line.separator")).getBytes();//
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//ctx.writeAndFlush(firstMessage);// 将请求消息发送给服务端
ByteBuf message=null;
for(int i=0;i<100;i++){
message=Unpooled.buffer(req.length);
message.writeBytes(req);
ctx.writeAndFlush(message);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
LOGGER.warning("Unexpected exception from downstrema : "
+ cause.getMessage());
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
/*ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");*/
String body=(String)msg;
System.out.println("Now is : " + body+"; the counter is : "+ ++counter);
}
}
原理分析
LineBasedFrameDecoder
工作原理是依次遍历ByteBuf中的可读字节,判断是否有换行符,如果有,就以此位置为结束位置,从可读索引到结束位置区间的字节就组成了一行。
StringDecoder
功能就是将接受到的对象转换为字符串,然后继续调用后面的handler。
LineBasedFrameDecoder+StringDecoder组合就是按行切换的文本解码器。
其他解码器
DelimiterBasedFrameDecoder可以自定义分隔符
FixedLengthFrameDecoder定长解码器。