netty: LengthFieldBasedFrameDecoder的用法示例

一、服务器端启动类:

复制代码
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);

        }

    }
}
相关推荐
刚入门的大一新生16 分钟前
C++初阶-list的模拟实现(难度较高)
开发语言·c++·list
你挚爱的强哥23 分钟前
Blob设置type为application/msword将document DOM节点转换为Word(.doc,.docx),并下载到本地
开发语言·c#·word
有梦想的攻城狮37 分钟前
spring中的ImportSelector接口详解
java·后端·spring·接口·importselector
晨曦~~38 分钟前
SpringCloudAlibaba和SpringBoot版本问题
java·spring boot·后端
Bt年44 分钟前
浮点数精度问题(CSP38思考)
开发语言·c++·算法
天天进步20151 小时前
Java应用性能监控与调优:从JProfiler到Prometheus的工具链构建
java·开发语言·prometheus
武昌库里写JAVA1 小时前
iview组件库:关于分页组件的使用与注意点
java·vue.js·spring boot·学习·课程设计
小伍_Five1 小时前
spark数据处理练习题番外篇【上】
java·大数据·spark·scala
海尔源码1 小时前
支持多语言的开源 Web 应用
java