利用protobuf格式进行前后端数据传输

创建student.proto文件,格式如下:

  1 syntax = "proto3";
  2 message Student{
  3     int64 id = 1;
  4     string name = 2;
  5     int64 age = 3;
  6 }
 

后端用python:

    通过protoc将.proto文件生成XX_pb2.py文件,然后import使用,在后端对.proto文件中变量进行赋值,然后对数据进行序列化SerializeToString(): serializes the message and returns it as a string. Note that the bytes are binary, not text; we only use the str type as a convenient container.

     生成命令:protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/XXX.proto

     创建对象:student = student_pb2.Student()

     为对象的各个变量赋值:

     def set_student():
        student.id = 8
        student.name = 'Sally'
        student.age = 17

    student = student_pb2.Student()

    st

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要实现前后之间的信息互通,可以使用 Protocol Buffers(简称 Protobuf)结合 Node.js 来实现。 首先,确保你已经安装了 Node.js 和 Protobuf 的相关依赖。 1. 定义消息格式:在一个 `.proto` 文件中定义消息的格式,该文件描述了前后之间通信的数据结构。例如,创建一个名为 `message.proto` 的文件,其中包含以下内容: ``` syntax = "proto3"; message Message { string content = 1; } ``` 2. 在前和后分别生成消息代码:使用 Protobuf 编译器将 `.proto` 文件编译成对应的代码。在终中运行以下命令: ``` protoc --js_out=import_style=commonjs,binary:./path/to/output/frontend message.proto protoc --js_out=import_style=commonjs,binary:./path/to/output/backend message.proto ``` 这将生成两个文件:`message_pb.js` 和 `message_pb.d.ts`,分别用于前和后。 3. 在前和后使用生成的代码:在前和后的代码中导入生成的代码文件以使用消息类型。例如,在 Node.js 中,可以这样导入和使用消息类型: ```javascript const { Message } = require('./path/to/output/backend/message_pb'); // 创建消息 const message = new Message(); message.setContent('Hello, world!'); // 将消息序列化为字节数组 const bytes = message.serializeBinary(); // 在网络上发送字节数组... // 在后接收到字节数组后,可以反序列化为消息类型 const receivedMessage = Message.deserializeBinary(bytes); // 在后获取消息内容 const content = receivedMessage.getContent(); console.log(content); // 输出 'Hello, world!' ``` 4. 在前后之间通过网络传递字节数组:将前序列化后的字节数组发送到后,并在后将字节数组反序列化为消息类型。 使用 Protocol Buffers 可以方便地定义和传输结构化数据,而且具有跨语言和跨平台的特性,适用于前后之间的数据交换。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值