您的位置:首页 > 理论基础 > 计算机网络

TCP粘包/拆包--利用DelimiterBasedFrameDecoder解决TCP粘包问题

2017-10-24 13:09 585 查看
前面我们介绍了利用LineBasedFrameDecoder解决TCP的粘包/拆包的问题,

现在我们继续介绍Netty的另外一种解码器--DelemiterBasedFrameDecoder。

1. DelimiterBasedFrameDecoder服务端开发

EchoServer.java

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.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class EchoServer {
private final static int port = 8080;

public static void main(String[] args) {
start();
}

private static void start() {
final EchoServerHandler serverHandler = new EchoServerHandler();
// 创建EventLoopGroup
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
// 创建EventLoopGroup
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
socketChannel.pipeline().addLast(
new DelimiterBasedFrameDecoder(1024, delimiter));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(serverHandler);
}
});

try {
// 异步地绑定服务器;调用sync方法阻塞等待直到绑定完成
ChannelFuture f = b.bind(port).sync();
// 获取Channel的CloseFuture,并且阻塞当前线程直到它完成
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 优雅的关闭EventLoopGroup,释放所有的资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}


2. EchoSeverHandler.java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter{
private int counter = 0;
@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 resp = Unpooled.copiedBuffer(body.getBytes());
ctx.writeAndFlush(resp);
}

/**
* 异常处理
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//打印异常栈跟踪
cause.printStackTrace();

// 关闭该Channel
ctx.close();
}
}
3. EchoClient.java
import io.netty.bootstrap.Bootstrap;
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;

import java.net.InetSocketAddress;

public class EchoClient {
private final static String HOST = "localhost";
private final static int PORT = 8080;

public static void start() {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new EchoClientHandler());
}
});
try {
ChannelFuture f = bootstrap.connect(HOST,PORT).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}

public static void main(String[] args) {
start();
}
}
4. EchoClientHandler.java
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@Sharable
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

private int counter;
static final String ECHO_REQ = "Hi, Welcome to Netty World!$_";

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println(
"This is "+ ++counter + " times receive server:[" + body +"]"
);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i = 0; i < 10; i++) {
ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
}
}
}

这里我们用"$_"做为分隔符、分别运行EchoServer和EchoClient

服务端控制台打印结果如下:

-------------------------------------------------

This is 1 times receive client [Hi, Welcome to Netty World!]
This is 2 times receive client [Hi, Welcome to Netty World!]
This is 3 times receive client [Hi, Welcome to Netty World!]
This is 4 times receive client [Hi, Welcome to Netty World!]
This is 5 times receive client [Hi, Welcome to Netty World!]
This is 6 times receive client [Hi, Welcome to Netty World!]
This is 7 times receive client [Hi, Welcome to Netty World!]
This is 8 times receive client [Hi, Welcome to Netty World!]
This is 9 times receive client [Hi, Welcome to Netty World!]
This is 10 times receive client [Hi, Welcome to Netty World!]
客户端控制台打印结果如下。
-------------------------------------------------------------------------------------------------

This is 1 times receive server:[Hi, Welcome to Netty World!]
This is 2 times receive server:[Hi, Welcome to Netty World!]
This is 3 times receive server:[Hi, Welcome to Netty World!]
This is 4 times receive server:[Hi, Welcome to Netty World!]
This is 5 times receive server:[Hi, Welcome to Netty World!]
This is 6 times receive server:[Hi, Welcome to Netty World!]
This is 7 times receive server:[Hi, Welcome to Netty World!]
This is 8 times receive server:[Hi, Welcome to Netty World!]
This is 9 times receive server:[Hi, Welcome to Netty World!]
This is 10 times receive server:[Hi, Welcome to Netty World!]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Netty 框架