首页 > 其他分享 >netty: Marshalling序列化示例

netty: Marshalling序列化示例

时间:2024-01-08 16:33:04浏览次数:35  
标签:netty 示例 io new import 序列化 public channel


一、请求对象和响应对象,分别要实现Serializable接口

package cn.edu.tju;

import java.io.Serializable;

public class UserRequest implements Serializable {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "UserRequest{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
package cn.edu.tju;

import java.io.Serializable;

public class UserResponse implements Serializable {
    private String username;
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserResponse{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}

二、返回Marshalling Encoder和Decoder的工厂类:

package cn.edu.tju;


import io.netty.handler.codec.marshalling.DefaultMarshallerProvider;
import io.netty.handler.codec.marshalling.DefaultUnmarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallingDecoder;
import io.netty.handler.codec.marshalling.MarshallingEncoder;
import io.netty.handler.codec.marshalling.UnmarshallerProvider;

import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;


public final class MarshallingCodeCFactory {

    public static MarshallingDecoder buildMarshallingDecoder() {
        final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
        MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);
        return decoder;
    }


    public static MarshallingEncoder buildMarshallingEncoder() {
        final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);
        MarshallingEncoder encoder = new MarshallingEncoder(provider);
        return encoder;
    }
}

三、服务器端handler和启动类

package cn.edu.tju;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MyObjectServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        UserRequest userRequest = (UserRequest) msg;
        System.out.println("server received message.....");
        System.out.println(userRequest);

        UserResponse userResponse = new UserResponse();
        userResponse.setUsername("amadeus liu");
        userResponse.setAge(32);
        ctx.writeAndFlush(userResponse);

    }
}
package cn.edu.tju;

import io.netty.bootstrap.ServerBootstrap;
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.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

public class NettyTcpObjectServer2 {
    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(MarshallingCodeCFactory.buildMarshallingDecoder());
                    pipeline.addLast(MarshallingCodeCFactory.buildMarshallingEncoder());



                    pipeline.addLast(new MyObjectServerHandler());
                }
            });

            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.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MyObjectClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active......");
        UserRequest userRequest = new UserRequest();
        userRequest.setUsername("amadeus liu");
        userRequest.setPassword("123456");
        ctx.writeAndFlush(userRequest);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("client received message......");
        UserResponse userResponse = (UserResponse) msg;
        System.out.println(userResponse);
    }
}
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.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class NettyTcpObjectClient2 {
    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(MarshallingCodeCFactory.buildMarshallingDecoder());
                    pipeline.addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                    pipeline.addLast(new MyObjectClientHandler());
                }
            });
            ChannelFuture channelFuture = bootStrap.connect(new InetSocketAddress(8899)).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
            group.shutdownGracefully();
        }

    }
}


标签:netty,示例,io,new,import,序列化,public,channel
From: https://blog.51cto.com/amadeusliu/9146824

相关文章

  • 使用Jsoup的Java网络爬虫示例:抓取在线考试平台试题数据
    网络爬虫是一种强大的工具,用于从互联网上收集信息。而在Java中,Jsoup是一款常用的HTML解析库,提供了便捷的API来解析、提取和操作HTML数据。在本文中,我们将深入探讨如何利用Jsoup库构建一个Java网络爬虫,并使用代理服务器来抓取在线考试平台的试题数据。介绍Jsoup和网络爬虫首先,我们将......
  • 基于Go语言的简单网络爬虫示例:获取智联招聘网页内容
    发起HTTP请求:使用Go的net/http包发起HTTP请求以获取网页内容。解析HTML内容:使用HTML解析器(如Go的golang.org/x/net/html包)来解析网页内容,找到你感兴趣的信息。提取目标数据:通过使用正则表达式或者更好的选择是HTML解析库来提取所需信息。存储或处理信息:将提取的信息存储到文件、数......
  • Java之序列化的详细解析
     3.序列化3.1概述Java提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该对象的数据、对象的类型和对象中存储的属性等信息。字节序列写出到文件之后,相当于文件中持久保存了一个对象的信息。反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反......
  • 【flink番外篇】9、Flink Table API 支持的操作示例(3)- 通过API查询表和使用窗口函数的
    Flink系列文章一、Flink专栏Flink专栏系统介绍某一知识点,并辅以具体的示例进行说明。1、Flink部署系列本部分介绍Flink的部署、配置相关基础内容。2、Flink基础系列本部分介绍Flink的基础部分,比如术语、架构、编程模型、编程指南、基本的datastreamapi用法、四大基......
  • Django quertset、set的序列化
    一、几种序列化importjson#序列化querysetdefxuliehuaQueryset(request):querylist=models.LsTable.objects.all()querylist_json=serializers.serialize("json",querylist)returnHttpResponse(querylist_json)#序列化setdefxuliehuaQueryset(......
  • 【flink番外篇】9、Flink Table API 支持的操作示例(2)- 通过Table API 和 SQL 创建视图
    Flink系列文章一、Flink专栏Flink专栏系统介绍某一知识点,并辅以具体的示例进行说明。1、Flink部署系列本部分介绍Flink的部署、配置相关基础内容。2、Flink基础系列本部分介绍Flink的基础部分,比如术语、架构、编程模型、编程指南、基本的datastreamapi用法、四大基......
  • C#中Queue队列的基本使用示例
       在C#中,Queue是一个内置的FIFO(First-In-First-Out)集合,这意味着元素在队列中的顺序与它们被添加的顺序相同,当且仅当从队列中移除元素时,元素出队的顺序才是正确的。Queue在.NETFramework中是一个泛型集合类型,这意味着你可以存储任何类型的元素。它提供了许多方法来操作队列,......
  • 敏捷研发管理流程及示例-Leangoo领歌|永久免费的敏捷开发工具
    ​ Leangoo领歌是一款永久免费的专业的敏捷开发管理工具,提供端到端敏捷研发管理解决方案,涵盖敏捷需求管理、任务协同、进展跟踪、统计度量等。Leangoo领歌上手快、实施成本低,可帮助企业快速落地敏捷,提质增效、缩短周期、加速创新。Leangoo领歌区别于传统项目管理软件,项目的需求......
  • MMBT3904资料手册参数解读及应用示例分享
    MMBT3904是一种三极小信号NPN晶体管。它具有低噪声、高放大倍数和较高的开关速度等特点。MMBT3904广泛应用于放大、开关和驱动电路等领域。它是一款常见的通用型晶体管,常被用于低功耗设备和数字电路中。常用于低电压、中电流放大应用。MMBT3904重要参数解读最大集电极电流(ICmax):这是......
  • 数据反序列化参数TypeReference
    使用jackson或者fastjson将json字符串反序列化成对象(以fastjson为例)TypeReference<AjaxResult<List<Person>>>typeReference=newTypeReference<AjaxResult<List<Person>>>(){};Stringjson="{\"code\":200,\"success\......