netty 自定义序列化


netty 自定义序列化

       

            

                                  

使用示例

         

fastjson序列化、反序列化对象

          

Person

@Data
public class Person {

    private String name;
    private Integer age;
}

            

Product

@Data
public class Product {

    private String name;
    private Float price;
    private Integer num;
}

          

***********

编解码器

       

CustomJsonEncoder

public class CustomJsonEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
        int startIndex = byteBuf.writerIndex();
        byteBuf.writeInt(0);
        byteBuf.writeBytes(message.getClassName().getBytes(StandardCharsets.UTF_8));  
        byteBuf.setInt(startIndex, byteBuf.writerIndex() - startIndex - 4);

        int bodyIndex = byteBuf.writerIndex();
        byteBuf.writeInt(0);
        byteBuf.writeBytes(JSON.toJSONBytes(message.getInstance()));
        byteBuf.setInt(bodyIndex, byteBuf.writerIndex() - bodyIndex -4);
    }
}

              

CustomsonDecoder

public class CustomJsonDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int classLength = byteBuf.readInt();
        byte[] className = new byte[classLength];
        byteBuf.readBytes(className);
        String name = new String(className);

        int bodyLength = byteBuf.readInt();
        byte[] instance = new byte[bodyLength];
        byteBuf.readBytes(instance);

        try {
            Class<?> clz = Class.forName(name);
            list.add(JSON.parseObject(instance,clz));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

           

***********

服务端

    

CustomServerHandler

public class CustomServerHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object object) throws Exception {
        System.out.println("读取到json数据:" + object);
    }
}

        

NettyServer

public class NettyServer {

    public static void startServer(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            channelPipeline.addLast(new CustomJsonDecoder());
                            channelPipeline.addLast(new CustomJsonEncoder());
                            channelPipeline.addLast(new CustomServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        startServer(8000);
    }
}

         

***********

客户端

   

CustomClientHandler

public class CustomClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Message message = new Message();
        message.setClassName(Person.class.getName());

        Person person = new Person();
        person.setName("瓜田李下");
        person.setAge(20);
        message.setInstance(person);

        System.out.println(message);
        ctx.channel().writeAndFlush(message);

        Message message2 = new Message();
        message2.setClassName(Product.class.getName());
        Product product = new Product();
        product.setName("苹果");
        product.setPrice(10f);
        product.setNum(10);
        message2.setInstance(product);
        ctx.channel().writeAndFlush(message2);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("客户端读取的响应数据:"+msg);
    }
}

         

NettyClient

public class NettyClient {

    public static void connect(String host, int port){
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            channelPipeline.addLast(new CustomJsonEncoder());
                            channelPipeline.addLast(new CustomJsonDecoder());
                            channelPipeline.addLast(new CustomClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8000;
        connect(host, port);
    }
}

             

***********

使用测试

  

点击运行后,服务端输出:

12:38:20.772 [main] DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.maxThreadLocalCharBufferSize: 16384
12:38:23.409 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 4096
12:38:23.409 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
12:38:23.409 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.chunkSize: 32
12:38:23.409 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.blocking: false
12:38:23.416 [nioEventLoopGroup-3-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkAccessible: true
12:38:23.416 [nioEventLoopGroup-3-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkBounds: true
12:38:23.419 [nioEventLoopGroup-3-1] DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@4ff5a067
读取到json数据:Person(name=瓜田李下, age=20)
读取到json数据:Product(name=苹果, price=10.0, num=10)

         

                  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自定义一个可序列化的 `io.netty.channel.Channel`,你需要实现以下步骤: 1. 创建一个 Java 类来实现你的 Channel。这个类需要继承 `io.netty.channel.AbstractChannel` 类,并且实现必要的构造函数和方法。 2. 为了实现信息的接收与发送,你需要覆盖 `io.netty.channel.AbstractChannel` 类中的 `doBind()`、`doConnect()`、`doWrite()`、`doReadMessages()` 方法。这些方法分别负责绑定、连接、写入数据和读取数据。 3. 为了实现序列化,你需要实现 `java.io.Serializable` 接口,并且在你的 Channel 类中添加 `writeObject()` 和 `readObject()` 方法。这些方法分别负责将 Channel 对象序列化成字节流和反序列化字节流成 Channel 对象。 下面是一个简单的示例代码: ```java import io.netty.channel.AbstractChannel; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class MyChannel extends AbstractChannel implements Serializable { // 构造函数 public MyChannel(Channel parent) { super(parent); } // 实现信息的接收与发送 @Override protected void doBind(SocketAddress localAddress) throws Exception { // 绑定操作 } @Override protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { // 连接操作 } @Override protected void doWrite(ChannelOutboundBuffer outboundBuffer) throws Exception { // 写入数据操作 } @Override protected void doReadMessages(List<Object> buf) throws Exception { // 读取数据操作 } // 实现序列化 private void writeObject(ObjectOutputStream out) throws IOException { // 将 Channel 对象序列化成字节流 } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // 将字节流反序列化Channel 对象 } } ``` 你可以根据你的具体需求进行更改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值