Protobuf

Protobuf基础

Protobuf

protobuf简介

  • protobuf是Google开源的一种数据格式 ,旨在通过减小数据size来提高传送效率

protobuf的JavaScript语言实现

  • 这里采用的是protobuf.js

使用方法一

  1. 创建包(实际就是创建命名空间)
  2. 创建消息
    • 若有嵌套子消息,则需要创建子消息,并添加到父消息中
  3. 将消息添加到包中
  4. 设置消息Field
  5. 创建消息数据
  6. 消息编码/解码
    // 1. 定义消息包
    const gamePackage = new Root().define("stockgame");
    // 2. 创建(父)消息
    const User = new Type("User"); // User 才是消息名称
    // 2.1 创建(子)消息
    const UserData = new Type("UserData");
    // 2.2 将子消息添加到父消息中
    User.add(UserData);
    // 3. 将父消息添加到包中`
    gamePackage.add(User);
    // 4. 设置父消息filed
    const codeField = new Field("code", 1, "uint32"); // Field不能共享
    User.add(codeField);
    User.add(new Field("data", 2, "UserData", "repeated"));
    // 4.1设置子消息filed
    UserData.add(new Field("a1", 1, "string"));
    UserData.add(new Field("a2", 2, "string"));
    UserData.add(new Field("code", 3, "uint32"));
    // 5.创建父消息数据
    const user = User.create({
        code: 200,
        data: [{ a1: "11", code: 300 }, { a2: "12" }]
    });
    // 创建其他消息
    const OtherMessage = new Type("Other");
    gamePackage.add(OtherMessage);
    OtherMessage.add(new Field("code1", 1, "uint32"));
    OtherMessage.add(new Field("data", 2, "User.UserData", "repeated")); // UserData消息重用
    const other = OtherMessage.create({
        code1: 800,
        data: [{ a1: "hello", code: 300 }, { a2: "world" }]
    });
    // 6.对消息编码
    const userInfoByEncode = User.encode(user).finish();
    const otherInfoByEncode = OtherMessage.encode(other).finish();
    console.log(User.decode(userInfoByEncode));
    console.log(OtherMessage.decode(otherInfoByEncode));