首页 > 其他分享 >netty: LengthFieldBasedFrameDecoder的用法示例

netty: LengthFieldBasedFrameDecoder的用法示例

时间:2024-01-02 12:36:23浏览次数:30  
标签:netty 示例 LengthFieldBasedFrameDecoder io new import public channel


一、服务器端启动类:

package cn.edu.tju;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

public class NettyTcpServer9 {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(16);

        try {
            ServerBootstrap  serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);



            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(4096, 0, 2, 0 ,2));
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new MyHandler9());
                }
            });

            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(8899))
                    .sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex){
            System.out.println(ex.getMessage());
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }



    }
}

二、服务器端handler

package cn.edu.tju;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;


@ChannelHandler.Sharable
public class MyHandler9 extends ChannelInboundHandlerAdapter {

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handler added......");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("channel read in MyHandler...");
        System.out.println(msg);
    }


}

三、客户端启动类:

package cn.edu.tju;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class NettyTcpClient9 {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootStrap = new Bootstrap();

            bootStrap.group(group);
            bootStrap.channel(NioSocketChannel.class);
            bootStrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new MyTcpClientHandler9());
                }
            });
            ChannelFuture channelFuture = bootStrap.connect(new InetSocketAddress(8899)).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
            group.shutdownGracefully();
        }

    }
}

四、客户端handler

package cn.edu.tju;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MyTcpClientHandler9 extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {


        for(int i = 0; i < 10; i ++){
            String str = "hello world";
            int length = str.length();
            ByteBuf buffer = Unpooled.buffer(length + 2);
            buffer.writeInt(length );
            for(int j = 0; j < length; j ++){
                buffer.writeByte(str.getBytes()[j]);

            }
            ctx.writeAndFlush(buffer);

        }

    }
}


标签:netty,示例,LengthFieldBasedFrameDecoder,io,new,import,public,channel
From: https://blog.51cto.com/amadeusliu/9067598

相关文章

  • netty源码:(38)ByteToMessageDecoder类
    ByteToMessageDecoder是一个解码器,是一个ChannelInboundHandlerAdapter,它用来将ByteBuf中的字节流解析成另外的消息格式。它的核心方法是decode,decode方法的in参数表示接收字节的来源,out参数表示节码之后输出的目的地。比如,StringDecoder继承了ByteToMessageDecoder,它的decod......
  • netty源码:(40)ReplayingDecoder
    ReplayingDecoder是ByteToMessageDecoder的子类,我们继承这个类时,也要实现decode方法,示例如下:packagecn.edu.tju;importio.netty.buffer.ByteBuf;importio.netty.channel.ChannelHandlerContext;importio.netty.handler.codec.ReplayingDecoder;importjava.nio.charset.C......
  • 【C++】STL 容器 - stack 堆栈容器 ① ( stack 堆栈容器特点 | stack 堆栈容器与 dequ
    文章目录一、stack堆栈容器简介1、stack堆栈容器引入2、stack堆栈容器特点3、stack堆栈容器与deque双端数组容器对比二、代码示例-stack堆栈容器简单示例1、代码示例2、执行结果一、stack堆栈容器简介1、stack堆栈容器引入C++语言中的STL标准模板库中的stac......
  • 上传到东萍象棋网大师对局的UBB示例【重要提示:同一盘棋千万不要书写重复字段内容】
    [DhtmlXQ][DhtmlXQ_ver]www_dpxq_com[/DhtmlXQ_ver][DhtmlXQ_title]北京刘永富和北京左治[/DhtmlXQ_title][DhtmlXQ_event]鑫聚缘大奖赛[/DhtmlXQ_event][DhtmlXQ_date]2023/12/30[/DhtmlXQ_date][DhtmlXQ_init]800,600[/DhtmlXQ_init][DhtmlXQ_result]和局[/DhtmlXQ_......
  • JavaScript圆形转多边形经纬度数组算法及示例
    前言在地理信息系统(GIS)和地图应用中,有时需要将圆形区域表示为多边形的经纬度数组对象。本文将介绍如何使用JavaScript实现圆形转多边形经纬度数组的算法,并提供一个示例来演示其用法。概述圆形转多边形经纬度数组的算法的目标是将给定的圆形区域表示为多边形的经纬度数组对象。这......
  • Python NumPy 生成随机数的方法及示例
    ​ NumPy是一个强大的库,用于数值计算,包括生成各种随机数。可以使用random.rand()、random.randn()、random.randint()、random.uniform()、random.normal()和random.seed()函数方法生成随机数。本文介绍生成随机数的方法,以及相关的示例代码。1、numpy.random.rand()numpy.ra......
  • 二进制、位运算和掩码运算、如何取某几位掩码,小白鼠测试示例
    1.二进制二进制是一种基于两个数字0和1的数制系统。它可以表示两种状态,即开和关。所有输入电脑的任何信息最终都要转化为二进制。目前通用的是ASCII码。最基本的单位为bit。在计算机科学中,二进制是最常用的数制系统,因为计算机内部的所有数据都是以二进制形式存储和处理的。在二......
  • 服务自动化管理脚本示例
    1、编写业务逻辑代码catnginx_auto.sh./etc/init.d/functionsfunctionStatus(){state=`systemctlstatusnginx|grep-wactive|awk'{print$2}'|xargs`if["$state"=="active"];thenaction"NginxisRunnin......
  • 【flink番外篇】7、flink的State(Keyed State和operator state)介绍及示例(2) - operator
    Flink系列文章一、Flink专栏Flink专栏系统介绍某一知识点,并辅以具体的示例进行说明。1、Flink部署系列本部分介绍Flink的部署、配置相关基础内容。2、Flink基础系列本部分介绍Flink的基础部分,比如术语、架构、编程模型、编程指南、基本的datastreamapi用法、四大基......
  • Spring Boot学习随笔- 集成MyBatis-Plus,第一个MP程序(环境搭建、@TableName、@TableId
    学习视频:【编程不良人】Mybatis-Plus整合SpringBoot实战教程,提高的你开发效率,后端人员必备!引言MyBatis-Plus是一个基于MyBatis的增强工具,旨在简化开发,提高效率。它扩展了MyBatis的功能,提供了许多实用的特性,包括强大的CRUD操作、条件构造器、分页插件、代码生成器等。MyBati......