Netty使用ProtoBuf发送数据实例

0.Protobuf简介

Protobuf是用来将对象序列化的,相类似的技术还有Json序列化等等。它是一种高效的结构化数据存储格式,可以用于结构化数据串行化(序列化)。它很适合做数据存储或RPC(远程过程调用)数据交换格式。目前很多公司 http+json → tcp+protobuf

  1. Protobuf 是以 message 的方式来管理数据的
  2. 支持跨平台、跨语言,即[客户端和服务器端可以是不同的语言编写的] (支持目前绝大多数语言,例如 C++、C#、Java、python 等
  3. 高性能,高可靠性
  4. 使用 protobuf 编译器能自动生成代码,Protobuf 是将类的定义使用.proto 文件进行描述。说明,在idea 中编写 .proto 文件时,会自动提示是否下载 .ptotot 编写插件. 可以让语法高亮。
  5. 然后通过 protoc.exe 编译器根据.proto 自动生成.java 文件

1.实例

1.1 导包

<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.6.1</version>
</dependency>

1.2 下载protoc.exe

下载解压后bin找到protoc.exe

protoc.exe下载

1.3 创建Student.proto文件

syntax = "proto3"; //版本
option java_outer_classname = "StudentPOJO"; //生成的外部类名,同时也是文件名

message Student { //会在StudentPojo 外部类生成一个内部类Student,他是真正发送的pojo对象
    int32 id = 1; //Student类中有一个属性名字为ID,类型为int32(protobuf类型),1表示序号,不是值
    string name = 2;
}

1.4 使用protoc.exe生成Java文件

将Student.proto放在protoc.exe同文件夹下使用命令行执行以下

protoc.exe --java_out=. Student.proto

即可生成StudentPOJO.java之后放入程序中使用

1.5 修改原来的服务端和客户端

1.5.1 客户端Handler修改channelActive
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // 发送一个Student对象到服务器
    StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(10).setName("jumper").build();
    ctx.writeAndFlush(student);
}
1.5.2 服务端Handler修改channelRead
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 读取从客户端发送的StudentPOJO.Student
        StudentPOJO.Student student = (StudentPOJO.Student) msg;
        System.out.println("客户端发送的数据 ID = " + student.getId() + "名字" + student.getName());
   }
1.5.3 客户端的initChannel
protected void initChannel(SocketChannel socketChannel) throws Exception {
    // 在pipeline中加入ProtoBufEncoder
    socketChannel.pipeline().addLast("encoder",new ProtobufEncoder());
    socketChannel.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器
}
1.5.4 服务端的initChannel
protected void initChannel(SocketChannel socketChannel) throws Exception {
    // 在pipeline加入ProtoBufDecoder
    // 指定对哪种对象进行解码
    socketChannel.pipeline().addLast("decoder",new ProtobufDecoder(StudentPOJO.Student.getDefaultInstance()));
    socketChannel.pipeline().addLast(new NettyServerHandler());
}

1.6 测试

先后启动服务端和客户端

结果如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
对于使用Netty 4.1和Protobuf的WebSocket编码器,你可以按照以下步骤进行设置: 1. 首先,确保你已经添加了NettyProtobuf的依赖到你的项目中。 2. 创建一个WebSocket编码器类,该类将负责将Protobuf消息编码为WebSocket帧。下面是一个示例代码: ```java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class ProtobufWebSocketEncoder extends MessageToByteEncoder<MessageLite> { @Override protected void encode(ChannelHandlerContext ctx, MessageLite msg, ByteBuf out) throws Exception { byte[] bytes = msg.toByteArray(); out.writeBytes(bytes); } } ``` 3. 在你的Netty初始化代码中,添加WebSocket编码器到你的ChannelPipeline中。下面是一个示例代码: ```java import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new HttpServerCodec()) .addLast(new HttpObjectAggregator(65536)) .addLast(new WebSocketServerProtocolHandler("/websocket")) .addLast(new ProtobufWebSocketEncoder()) .addLast(new YourCustomWebSocketHandler()); } } ``` 在上面的代码中,`YourCustomWebSocketHandler`是你自己实现的处理WebSocket消息的处理器。 4. 最后,在你的Netty服务器启动代码中,绑定正确的端口并启动服务器。下面是一个示例代码: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class WebSocketServer { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new WebSocketServerInitializer()); ChannelFuture f = b.bind(8080).sync(); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` 确保将端口号8080更改为你实际使用的端口号。 以上就是使用Netty 4.1和Protobuf的WebSocket编码器的基本设置。请根据你的实际需求进行适当的修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jumper17

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值