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

相关文章

将Python应用部署到生产环境的小技巧分享

《将Python应用部署到生产环境的小技巧分享》文章主要讲述了在将Python应用程序部署到生产环境之前,需要进行的准备工作和最佳实践,包括心态调整、代码审查、测试覆盖率提升、配置文件优化、日志记录完... 目录部署前夜:从开发到生产的心理准备与检查清单环境搭建:打造稳固的应用运行平台自动化流水线:让部署像

Linux中Curl参数详解实践应用

《Linux中Curl参数详解实践应用》在现代网络开发和运维工作中,curl命令是一个不可或缺的工具,它是一个利用URL语法在命令行下工作的文件传输工具,支持多种协议,如HTTP、HTTPS、FTP等... 目录引言一、基础请求参数1. -X 或 --request2. -d 或 --data3. -H 或

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

Node.js 中 http 模块的深度剖析与实战应用小结

《Node.js中http模块的深度剖析与实战应用小结》本文详细介绍了Node.js中的http模块,从创建HTTP服务器、处理请求与响应,到获取请求参数,每个环节都通过代码示例进行解析,旨在帮... 目录Node.js 中 http 模块的深度剖析与实战应用一、引言二、创建 HTTP 服务器:基石搭建(一

java中VO PO DTO POJO BO DO对象的应用场景及使用方式

《java中VOPODTOPOJOBODO对象的应用场景及使用方式》文章介绍了Java开发中常用的几种对象类型及其应用场景,包括VO、PO、DTO、POJO、BO和DO等,并通过示例说明了它... 目录Java中VO PO DTO POJO BO DO对象的应用VO (View Object) - 视图对象

Go信号处理如何优雅地关闭你的应用

《Go信号处理如何优雅地关闭你的应用》Go中的优雅关闭机制使得在应用程序接收到终止信号时,能够进行平滑的资源清理,通过使用context来管理goroutine的生命周期,结合signal... 目录1. 什么是信号处理?2. 如何优雅地关闭 Go 应用?3. 代码实现3.1 基本的信号捕获和优雅关闭3.2

正则表达式高级应用与性能优化记录

《正则表达式高级应用与性能优化记录》本文介绍了正则表达式的高级应用和性能优化技巧,包括文本拆分、合并、XML/HTML解析、数据分析、以及性能优化方法,通过这些技巧,可以更高效地利用正则表达式进行复杂... 目录第6章:正则表达式的高级应用6.1 模式匹配与文本处理6.1.1 文本拆分6.1.2 文本合并6

python中的与时间相关的模块应用场景分析

《python中的与时间相关的模块应用场景分析》本文介绍了Python中与时间相关的几个重要模块:`time`、`datetime`、`calendar`、`timeit`、`pytz`和`dateu... 目录1. time 模块2. datetime 模块3. calendar 模块4. timeit

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取