FixedLengthFrameDecoder是固定长度解码器,它能按照指定的长度对消息进行自动解码,开发者不需要考虑TCP粘包/拆包问题
EchoServer2.java
/**
* FixedLengthFrameDecoder解决半包/粘包问题
* 通过控制台cmd telnet 127.0.0.1 8089,每满输入20个字符,就会在eclipse打印出相应的20个字符
* @author author
*
*/
public class EchoServer2 {
private final int port =8089;
public static void main(String[] args) {
new EchoServer2().start();
}
private void start() {
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new FixedLengthFrameDecoder(20));//限定长度20就输出
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new EchoServerHandler2());
}
});
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
group.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
EchoServerHandler2.java
public class EchoServerHandler2 extends ChannelInboundHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("receive client:["+msg+"]");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}