博客概述
本博客是上篇文章的续集,主要讲述netty实现定长数据包解码器的案例。
服务器端
package fixed;
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.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import java.nio.charset.Charset;
/**
* @Auther: ;李泽
* @Date: 2019/3/4 22:04
* @Description:
*/
public class NettyServer {
private int port;
public NettyServer(int port) {
this.port = port;
}
public void run() throws Exception {
/*
bossGroup负责接受网络连接以及建立连接
workerGroup负责具体的网络通讯
*/
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
/*
ServerBootstrap 是一个启动服务器端NIO服务的辅助启动类。
*/
ServerBootstrap b = new ServerBootstrap();
//给启动器配置两个线程组,前一个是接受连接,后一个具体干活
b.group(bossGroup, workerGroup)
//这里我们指定使用NioServerSocketChannel类来说明服务器端接受的tcp连接是nio模式的。
.channel(NioServerSocketChannel.class)
/*
这里的事件处理类经常会被用来处理一个最近的已经接收的Channel。ChannelInitializer是一个特殊的处理类,
他的目的是帮助使用者配置一个新的Channel。也许你想通过增