Netty中分隔符和定长解码器的应用

2024-06-23 12:32

本文主要是介绍Netty中分隔符和定长解码器的应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一.使用DelimiterBasedFrameDecoder自动完成以分隔符作为结束标志的解码

1.1 DelimiterBasedFrameDecoder服务端开发

1.1.1 EchoServer实现

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;

importio.netty.channel.nio.NioEventLoopGroup;

importio.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioServerSocketChannel;

importio.netty.handler.codec.DelimiterBasedFrameDecoder;

importio.netty.handler.codec.LineBasedFrameDecoder;

importio.netty.handler.codec.string.StringDecoder;

import io.netty.handler.logging.LogLevel;

import io.netty.handler.logging.LoggingHandler;

/*

 * 利用DelimiterBasedFrameDecoder完成以分隔符作为码流结束的标识

 */

public class EchoServer {

        

         publicvoid bind(int port) throws Exception{

                   //配置服务端的NIO线程组

                   EventLoopGroupbossGroup =new NioEventLoopGroup();

                   EventLoopGroupworkerGroup =new NioEventLoopGroup();

         try{

                   //用于启动NIO服务器的辅助启动类,降低服务端的开发复杂度

                   ServerBootstrapb=new ServerBootstrap();

                   b.group(bossGroup,workerGroup).

                   channel(NioServerSocketChannel.class)

                   .option(ChannelOption.SO_BACKLOG,100)

                   .handler(newLoggingHandler(LogLevel.INFO))

                   .childHandler(newChannelInitializer<SocketChannel>() {

                            @Override

                            publicvoid initChannel(SocketChannel ch) throws Exception{

                                     ByteBufdelimiter=Unpooled.copiedBuffer("$_".getBytes());

                                     ch.pipeline().addLast(

                                                        newDelimiterBasedFrameDecoder(1024,delimiter)); // 单条消息最大长度:1024

                                     ch.pipeline().addLast(newStringDecoder());

                                     ch.pipeline().addLast(newEchoServerHandler());

                            }

                            });

                           

                  

                   //绑定端口,同步等待成功

                   ChannelFuturef=b.bind(port).sync();

                   //等待服务端监听端口关闭

                   f.channel().closeFuture().sync();

        

                  

         }catch (Exception e) {

                   //TODO: handle exception

         }finally{

                   //优雅退出,释放线程池资源

                   bossGroup.shutdownGracefully();

                   workerGroup.shutdownGracefully();

         }

        

         }

 

        

         publicstatic void main(String[] args) throws Exception{

                   intport=8080;

                   if(args!=null&&args.length>0){

                            try{

                                     port=Integer.valueOf(args[0]);

                            }catch (NumberFormatException e) {

                                     //TODO: handle exception

                            }

                   }

                   newEchoServer().bind(port);

         }}

1.1.2 EchoServerHandler实现

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

/*

 * 利用LineBasedFrameDecoder解决TCP粘包问题

 */

public classEchoServerHandler extends ChannelHandlerAdapter{

     

   int counter =0;

   @Override

   public voidchannelRead(ChannelHandlerContext ctx,Object msg)throwsException{

     

      Stringbody=(String)msg;

      System.out.println("This is"+++counter+"times receive client: ["+body+"]" );

      body+="$_";

         ByteBufecho=Unpooled.copiedBuffer(body.getBytes());

         ctx.writeAndFlush(echo);

   }

 

  

   @Override

   public voidexceptionCaught(ChannelHandlerContext ctx,Throwable cause){

      cause.printStackTrace();

      ctx.close();  // 发生异常,关闭链路

   }

}

1.2 DelimitedBasedFrameDecoder客户端开发

1.2.1 EchoClient实现

import client.TimeClient;

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;

importio.netty.channel.nio.NioEventLoopGroup;

importio.netty.channel.socket.SocketChannel;

importio.netty.channel.socket.nio.NioSocketChannel;

importio.netty.handler.codec.DelimiterBasedFrameDecoder;

importio.netty.handler.codec.string.StringDecoder;

 

public class EchoClient {

        

         publicvoid connect(int port,String host) throws Exception{

                   //配置客户端NIO线程组

                   EventLoopGroupgroup=new NioEventLoopGroup();

                   try{

                            Bootstrapb=new Bootstrap();

                            b.group(group).channel(NioSocketChannel.class)

                            .option(ChannelOption.TCP_NODELAY,true)

                            .handler(newChannelInitializer<SocketChannel>() {

                                     @Override

                                     publicvoid initChannel(SocketChannel ch) throws Exception{

                                               ByteBufdelimiter=Unpooled.copiedBuffer("$_".getBytes());

                                               ch.pipeline().addLast(newDelimiterBasedFrameDecoder(1024,delimiter));

                                               ch.pipeline().addLast(newStringDecoder());

                                               ch.pipeline().addLast(newEchoClientHandler());

                                     }

                            });

                            //发起异步连接操作

                            ChannelFuturef=b.connect(host,port).sync();

                            //等待客户端链路关闭

                            f.channel().closeFuture().sync();

                   }catch (Exception e) {

                            //TODO: handle exception

                   }finally{

                            //优雅退出,释放NIO线程组

                            group.shutdownGracefully();

                   }

         }

        

         publicstatic void main(String[] args) throws Exception{

                   intport=8080;

                   if(args!=null&&args.length>0){

                            try{

                                     port=Integer.valueOf(args[0]);

                                    

                            }catch (NumberFormatException e) {

                                     //TODO: handle exception

                                    

                            }

                            newTimeClient().connect(port,"127.0.0.1");

                   }

         }

 

}

1.2.2 EchoClientHandler实现

import io.netty.buffer.Unpooled;

importio.netty.channel.ChannelHandlerAdapter;

importio.netty.channel.ChannelHandlerContext;

 

public class EchoClientHandler extendsChannelHandlerAdapter{

        private int counter;

        static final String ECHO_REQ="Welcome to Netty.$_";

        

        public EchoClientHandler(){

                 

        }

        

        @Override

        public void channelActive(ChannelHandlerContext ctx){

                 for(int i=0;i<10;i++){

                           ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));

                 }

        }

        

        public void channelRead(ChannelHandlerContext ctx,Object msg) throwsException{

                 ctx.flush();

        }

        

        @Override

        public voidexceptionCaught(ChannelHandlerContext ctx,Throwable cause){

                 cause.printStackTrace();

                 ctx.close();

        }

}

二.使用FiexLengthFrameDecoder定长解码器进行自动解码

2.1 FixLengthFrameDecoder服务的开发

2.1.1 EchoServer实现

package fixedlength;

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;

importio.netty.channel.nio.NioEventLoopGroup;

importio.netty.channel.socket.SocketChannel;

importio.netty.channel.socket.nio.NioServerSocketChannel;

importio.netty.handler.codec.DelimiterBasedFrameDecoder;

import io.netty.handler.codec.FixedLengthFrameDecoder;

importio.netty.handler.codec.LineBasedFrameDecoder;

importio.netty.handler.codec.string.StringDecoder;

import io.netty.handler.logging.LogLevel;

importio.netty.handler.logging.LoggingHandler;

/*

 * 利用FixedLengthFrameDecoder固定解码长度

 */

public class EchoServer {

        

         publicvoid bind(int port) throws Exception{

                   //配置服务端的NIO线程组

                   EventLoopGroupbossGroup =new NioEventLoopGroup();

                   EventLoopGroupworkerGroup =new NioEventLoopGroup();

         try{

                   //用于启动NIO服务器的辅助启动类,降低服务端的开发复杂度

                   ServerBootstrapb=new ServerBootstrap();

                   b.group(bossGroup,workerGroup).

                   channel(NioServerSocketChannel.class)

                   .option(ChannelOption.SO_BACKLOG,100)

                   .handler(newLoggingHandler(LogLevel.INFO))

                   .childHandler(newChannelInitializer<SocketChannel>() {

                            @Override

                            publicvoid initChannel(SocketChannel ch) throws Exception{

                                     ByteBufdelimiter=Unpooled.copiedBuffer("$_".getBytes());

                                     ch.pipeline().addLast(

                                                        newFixedLengthFrameDecoder(20)); // 固定解码长度为20

                                     ch.pipeline().addLast(newStringDecoder());

                                     ch.pipeline().addLast(newEchoServerHandler());

                            }

                            });

                           

                  

                   //绑定端口,同步等待成功

                   ChannelFuturef=b.bind(port).sync();

                   //等待服务端监听端口关闭

                   f.channel().closeFuture().sync();

        

                  

         }catch (Exception e) {

                   //TODO: handle exception

         }finally{

                   //优雅退出,释放线程池资源

                   bossGroup.shutdownGracefully();

                   workerGroup.shutdownGracefully();

         }

        

         }

 

        

         publicstatic void main(String[] args) throws Exception{

                   intport=8080;

                   if(args!=null&&args.length>0){

                            try{

                                     port=Integer.valueOf(args[0]);

                            }catch (NumberFormatException e) {

                                     //TODO: handle exception

                            }

                   }

                   newEchoServer().bind(port);

         }

 

}

2.1.2 EchoServerHandler实现

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

/*

 * 打印读取的消息

 */

public classEchoServerHandler extends ChannelHandlerAdapter{

         

   @Override

   public voidchannelRead(ChannelHandlerContext ctx,Object msg)throwsException{

      System.out.println("Receive client:["+msg+"]");

     

   }

   @Override

   public voidexceptionCaught(ChannelHandlerContext ctx,Throwable cause){

      cause.printStackTrace();

      ctx.close();  // 发生异常,关闭链路

   }

}

  利用FixedLengthFrameDecoder解码器,无论一次接受多少数据报,它都会按照构造函数中固定长度进行解码

这篇关于Netty中分隔符和定长解码器的应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1087165

相关文章

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”

如何确定哪些软件是Mac系统自带的? Mac系统内置应用查看技巧

《如何确定哪些软件是Mac系统自带的?Mac系统内置应用查看技巧》如何确定哪些软件是Mac系统自带的?mac系统中有很多自带的应用,想要看看哪些是系统自带,该怎么查看呢?下面我们就来看看Mac系统内... 在MAC电脑上,可以使用以下方法来确定哪些软件是系统自带的:1.应用程序文件夹打开应用程序文件夹

Python Flask 库及应用场景

《PythonFlask库及应用场景》Flask是Python生态中​轻量级且高度灵活的Web开发框架,基于WerkzeugWSGI工具库和Jinja2模板引擎构建,下面给大家介绍PythonFl... 目录一、Flask 库简介二、核心组件与架构三、常用函数与核心操作 ​1. 基础应用搭建​2. 路由与参

Spring Boot中的YML配置列表及应用小结

《SpringBoot中的YML配置列表及应用小结》在SpringBoot中使用YAML进行列表的配置不仅简洁明了,还能提高代码的可读性和可维护性,:本文主要介绍SpringBoot中的YML配... 目录YAML列表的基础语法在Spring Boot中的应用从YAML读取列表列表中的复杂对象其他注意事项总