Netty笔记5----定长解码器解决粘包

Netty笔记5----定长解码器解决粘包

  • 服务端启动类


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.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class EchoServer {
    public void bind(int port) throws Exception {
   // 配置服务端的NIO线程组
   EventLoopGroup bossGroup = new NioEventLoopGroup();
   EventLoopGroup workerGroup = new NioEventLoopGroup();
   try {
       ServerBootstrap b = new ServerBootstrap();
       b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .option(ChannelOption.SO_BACKLOG, 100)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(new ChannelInitializer<SocketChannel>() {
         @Override
         public void initChannel(SocketChannel ch)
            throws Exception {
             ch.pipeline().addLast(
                new FixedLengthFrameDecoder(20));
             ch.pipeline().addLast(new StringDecoder());
             ch.pipeline().addLast(new EchoServerHandler());
         }
          });

       // 绑定端口,同步等待成功
       ChannelFuture f = b.bind(port).sync();

       // 等待服务端监听端口关闭
       f.channel().closeFuture().sync();
   } finally {
       // 优雅退出,释放线程池资源
       bossGroup.shutdownGracefully();
       workerGroup.shutdownGracefully();
   }
    }

    public static void main(String[] args) throws Exception {
   int port = 8080;
   if (args != null && args.length > 0) {
       try {
      port = Integer.valueOf(args[0]);
       } catch (NumberFormatException e) {
      // 采用默认值
       }
   }
   new EchoServer().bind(port);
    }
}
  • 服务端实现类



import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler 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) {
   cause.printStackTrace();
   ctx.close();// 发生异常,关闭链路
    }
}
  • ch.pipeline().addLast(new FixedLengthFrameDecoder(20));ch.pipeline().addLast(new StringDecoder());

在服务端加入指定长度解码器,会将收到的报文按照指定长度解析。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值