• flatbuffers 代码集成


    参考上次的操作,因为默认的不是nodejs 模块友好的,使用了typescript 同时集成了代码

    schema

    union HttpCommand {
        HttpQuery,
        HttpResultSet,
        HttpError
    }
     
    table HttpMessage {
        message_id: uint;
        command: HttpCommand;
    }
     
    table HttpQuery {
        query: string;
    }
     
    table HttpError {
        error: string;
    }
     
    table HttpResultSet {
        columns: [string];
        rows: [HttpRow];
    }
     
    table HttpRow {
        values: [HttpColumnValue];
    }
     
    table HttpColumnValue {
        string_value: string;
    }
    root_type HttpMessage;

    生成代码

    flatc --ts http_message.fbs

    生成nodejs 模块友好的代码

    使用tsc 编译

    {
      "name": "first",
      "version": "1.0.0",
      "main": "index.js",
      "license": "MIT",
      "dependencies": {
        "flatbuffers": "^1.12.0"
      },
      "scripts": {
        "watch": "tsc --watch"
      },
      "devDependencies": {
        "@types/flatbuffers": "^1.10.0",
        "typescript": "^4.2.3"
      }
    }

    代码集成

    const flatbuffers = require("flatbuffers").flatbuffers
    const {HttpQuery,HttpMessage,HttpCommand} = require("./http_message_generated")
    const builder = new flatbuffers.Builder(1024);
    const queryOffset = builder.createString("dalongrong");
    const httpQueryOffset = HttpQuery.createHttpQuery(builder,queryOffset);
    const messageId = 10000
    const message = HttpMessage.createHttpMessage(builder, messageId, HttpCommand.HttpQuery, httpQueryOffset);
    builder.finish(message);
    let msg =builder.asUint8Array()
    const buf = new flatbuffers.ByteBuffer(msg);
    const myHttpMessage = HttpMessage.getRootAsHttpMessage(buf);
    console.log("command:",myHttpMessage.commandType())
    if (myHttpMessage.commandType()==HttpCommand.HttpQuery){
        const httpQuery = myHttpMessage.command(new HttpQuery());
        console.log("query:",httpQuery.query())
    }

    运行效果

    参考资料

    https://google.github.io/flatbuffers/flatbuffers_guide_use_typescript.html
    https://google.github.io/flatbuffers/flatbuffers_guide_using_schema_compiler.html

  • 相关阅读:
    [转]优秀的程序员不会觉得累成狗是一种荣耀
    .NET读写Excel工具Spire.XlS使用(DataExport )
    WPF之Binding深入探讨
    第一个WPF应用程序
    Visio作图
    唯一的重复元素
    Strange Problem O(∩_∩)O~
    数据库知识点①
    HDU 2825 Wireless Password
    POJ 1625 Censored!
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/14590501.html
Copyright © 2020-2023  润新知