之前我们介绍了用特殊分隔符来分割每个报文,但是如果传输的数据中恰好有个特殊分隔符,它将会被拆分成多个,于是,为了进一步避免这个问题,还有一种解决方案是在两端的channelPipeline
中用一个固定长度来区分,这样也可以解决粘包半包的问题
1.Server
package splicing.fixed;
import constant.Constant;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import java.net.InetSocketAddress;
public class FixedLengthEchoServer {
public static final String RESPONSE = "Welcome to Netty";
public static void main(String[] args) throws InterruptedException {
FixedLengthEchoServer fixedLengthEchoServer = new FixedLengthEchoServer();
System.out.println("服务器即将启动");
fixedLengthEchoServer.start();
}
public void start() throws InterruptedException {
FixedLengthServerHandler serverHandler = new FixedLengthServerHandler();
EventLoopGroup group = new NioEventLoopGroup();// 线程组
try {
// 服务端启动必须
ServerBootstrap b = new ServerBootstrap();
b.group(group)// 将线程组传入
.channel(NioServerSocketChannel.class) // 指定使用NIO进行网络传输
.localAddress(new InetSocketAddress(Constant.DEFAULT_PORT)) // 指定服务器监听端口
// 服务端每