微信小程序websocket使用protobuf,发送arraybuffer

news2024/7/4 4:53:30

❤️砥砺前行,不负余光,永远在路上❤️

目录

    • 前言
    • 一、如何在小程序websocket中使用 Protobuf 发送buffer
    • 二、使用过程遇到的坑(版本问题)
      • 1、需要注意下Protobuf版本 使用 protobufjs@6.8.6最好,我在使用的时候安装7.多 莫名奇妙 pbjs 用不起
      • 2、websocket中发送 buffer
    • 三、完整步骤
      • 1、下载protoBufferForWechat 导入到项目中
      • 2、安装pbjs工具6.8.6
      • 3、验证是否安装成功
      • 4、转换proto文件
      • 5、最后使用
      • 6、websocket中发送buffer
      • 7、处理服务端返回的buffer
    • 四、小程序中的效果

前言

这是一次继前文websocket的一个更新:小程序中使用websocket,区分房间、空间 现在遇到了一个需求是小程序接入 io-game 的websocket 和unity 游戏端同时使用一个websocket,io-game那边收发websocket消息都是采用 Protobuf 处理的。

一、如何在小程序websocket中使用 Protobuf 发送buffer

参考项目:https://github.com/Zhang19910325/protoBufferForWechat/tree/master

二、使用过程遇到的坑(版本问题)

1、需要注意下Protobuf版本 使用 protobufjs@6.8.6最好,我在使用的时候安装7.多 莫名奇妙 pbjs 用不起

在这里插入图片描述

cnpm install -g protobufjs@6.8.6

然后执行pbjs即可
在这里插入图片描述

2、websocket中发送 buffer

支持string和arraybuffer类型,所以把Uint8Array直接转换为arraybuffer

new Uint8Array([...buffer]).buffer

三、完整步骤

1、下载protoBufferForWechat 导入到项目中

git clone https://github.com/Zhang19910325/protoBufferForWechat.git 

2、安装pbjs工具6.8.6

cnpm install -g protobufjs@6.8.6
//or
yarn add globle protobufjs@6.8.6

3、验证是否安装成功

执行pbjs出现如下信息即可

protobuf.js v6.7.0 CLI for JavaScript

Translates between file formats and generates static code.

  -t, --target     Specifies the target format. Also accepts a path to require a custom target.

                   json          JSON representation
                   json-module   JSON representation as a module
                   proto2        Protocol Buffers, Version 2
                   proto3        Protocol Buffers, Version 3
                   static        Static code without reflection (non-functional on its own)
                   static-module Static code without reflection as a module

  -p, --path       Adds a directory to the include path.

  -o, --out        Saves to a file instead of writing to stdout.

  --sparse         Exports only those types referenced from a main file (experimental).

  Module targets only:

  -w, --wrap       Specifies the wrapper to use. Also accepts a path to require a custom wrapper.

                   default   Default wrapper supporting both CommonJS and AMD
                   commonjs  CommonJS wrapper
                   amd       AMD wrapper
                   es6       ES6 wrapper (implies --es6)
                   closure   A closure adding to protobuf.roots where protobuf is a global

  --dependency     Specifies which version of protobuf to require. Accepts any valid module id

  -r, --root       Specifies an alternative protobuf.roots name.

  -l, --lint       Linter configuration. Defaults to protobuf.js-compatible rules:

                   eslint-disable block-scoped-var, no-redeclare, no-control-regex, no-prototype-builtins

  --es6            Enables ES6 syntax (const/let instead of var)

  Proto sources only:

  --keep-case      Keeps field casing instead of converting to camel case.

  Static targets only:

  --no-create      Does not generate create functions used for reflection compatibility.
  --no-encode      Does not generate encode functions.
  --no-decode      Does not generate decode functions.
  --no-verify      Does not generate verify functions.
  --no-convert     Does not generate convert functions like from/toObject
  --no-delimited   Does not generate delimited encode/decode functions.
  --no-beautify    Does not beautify generated code.
  --no-comments    Does not output any JSDoc comments.

  --force-long     Enfores the use of 'Long' for s-/u-/int64 and s-/fixed64 fields.
  --force-number   Enfores the use of 'number' for s-/u-/int64 and s-/fixed64 fields.
  --force-message  Enfores the use of message instances instead of plain objects.

usage: pbjs [options] file1.proto file2.json ...  (or pipe)  other | pbjs [options] -

4、转换proto文件

例如:我的Req_LoginVerify.proto文件

syntax = "proto3";

// {classComment}
message Req_LoginVerify {
  // 用户id
  int64 userId = 1;
  // 场次id
  int64 sessionId = 2;
  // 房间总人数
  int32 roomCountNum = 3;

}

运行之后会生成一个 Req_LoginVerify.json文件

pbjs -t json Req_LoginVerify.proto > Req_LoginVerify.json

内容为:

{
  "nested": {
    "Req_LoginVerify": {
      "fields": {
        "userId": {
          "type": "int64",
          "id": 1
        },
        "sessionId": {
          "type": "int64",
          "id": 2
        },
        "roomCountNum": {
          "type": "int32",
          "id": 3
        }
      }
    }
  }
}

但此时的json文件我们不能直接使用,不过我们可以将json对象取出放到小程序项目当中去,比如在小程序项目中新建一个Req_LoginVerify.js,内容为

module.exports = {
        "nested": {
                "Req_LoginVerify": {
                        "fields": {
                                "userId": {
                                        "type": "int64",
                                        "id": 1
                                },
                                "sessionId": {
                                        "type": "int64",
                                        "id": 2
                                },
                                "roomCountNum": {
                                        "type": "int32",
                                        "id": 3
                                }
                        }
                }
        }
}

5、最后使用

注意我的文件结构:

var protobuf = require('../../weichatPb/protobuf.js');
var loginConfig = require('../../proto/Req_LoginVerify');//加载awesome.proto对应的json
var Login = protobuf.Root.fromJSON(loginConfig);
var LoginMsg = Login.lookupType("Req_LoginVerify");//这就是我们的Message类

在这里插入图片描述

6、websocket中发送buffer

sendSocketMessage: function () {
                if (this.data.socketOpen) {
                        var payload = {
                                userId: 1,
                                sessionId: 12,
                                roomCountNum: 6
                        };
                        var message = LoginMsg.create(payload);
                        var buffer = LoginMsg.encode(message).finish();
                        console.log("buffer", buffer);
                        wx.sendSocketMessage({
                                data: new Uint8Array([...buffer]).buffer
                        })
                }
        },

7、处理服务端返回的buffer

wx.onSocketMessage(function (res) {
        console.log('接收到服务器发送的原始数据:', res.data)
        var deMessage = LoginMsg.decode(res.data);
        console.log("解析buffer之后的数据", deMessage);

})

四、小程序中的效果

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/598977.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

1_7后端优化

后端优化是指将一段时间内相机所有关键帧的位姿、内参、每个点3维坐标作为参数进行优化,得到最优的内、外参;利用的方法主要是Bundle Adjustment。 所谓Bundle Adjustment可以理解为从任意特征点发射出来的几束光线,它们会在几个相机的成像平…

寄存器-汇编复习(2)

通过阅读本文小节内容,可以清楚的明白汇编承接的能力和机器语言,高级语言之间的表达关系。文中虽然讨论16位cpu,最新的64或以后的128理论都一样的,类推就好了。 继续将 通用寄存器-汇编复习(1)_luozhonghua2000的博客-CSDN博客 …

很多人打商标的主意,悄悄埋伏

很多人在打商标的主意,等着抢劫呢 等你的品牌结了果实,然后出手勒索 趣讲大白话:鬼子进村,打枪的不要 【趣讲信息科技183期】 **************************** 有些公司申请几千件商标 有公司一个月申请100件 春江水暖贼先知 有一条…

WSL2网络配置

WSL2越来越好用了,但是在windows下使用clash时,配置WSL2的网络很麻烦,通常使用设置环境变量export ALL_PROXY"http://127.0.0.1:8000"的方式有很大的弊端,例如pip和conda就不会走代理。 经过我亲身体验,最好…

基于小脑模型神经网络的轨迹跟踪研究(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 ⛳️座右铭&a…

模拟退火算法(附简单案例及详细matlab源码)

作者:非妃是公主 专栏:《智能优化算法》 博客地址:https://blog.csdn.net/myf_666 个性签:顺境不惰,逆境不馁,以心制境,万事可成。——曾国藩 文章目录 专栏推荐序一、概论二、物理退火1. 加温…

MyBatis - CRUD 操作

文章目录 1.环境配置1.1 导入相关依赖1.2 基本配置1.3 数据模型 2.基于 XML 开发2.1 创建 Mapper 接口2.2 创建 XML 映射文件2.3 insert2.4 select2.5 delete2.6 update2.7 编写单元测试 3.基于注解开发3.1 常用注解3.2 创建 Mapper 接口 MyBatis 支持通过 XML 和注解两种方式来…

chatgpt赋能python:Python运行程序没反应怎么办?

Python运行程序没反应怎么办? Python作为一种高级编程语言,已经成为了很多开发者的首选语言。然而,在使用Python编写程序时,有时候会出现运行程序却没有任何反应的情况。这是什么原因导致的呢?本文将为大家介绍Python…

单例模式的饿/懒汉模式

目录 1. 什么是单例模式2. 饿汉模式2.1 饿汉模式概念2.2 饿汉模式代码 3. 懒汉模式3.1 懒汉模式概念3.2 单线程情况下的懒汉模式3.3 单例模式的写法(保证线程安全) 4. wait 和 sleep 的区别 1. 什么是单例模式 保证某个类在程序中只存在一份实例,而不会创建多个实例…

Apache Kafka - 跨集群数据镜像 MirrorMaker

文章目录 概述跨集群数据镜像的原理MirrorMaker配置小结 概述 在分布式系统中,数据镜像是一项重要的功能,它可以将数据从一个集群复制到另一个集群,以保证数据的高可用性和容错性。Apache Kafka是一个流处理平台,它提供了一种跨集…

程序设计综合实习(C语言):学生成绩单制作

一、目的 1.掌握结构体变量及数组的定义、赋值、初始化、输入、输出 2.结构体数组的操作。 二、实习环境 Visual Stdio 2022 三、实习内容、步骤与要求 1.定义一个结构体数组,存放10个学生的学号,姓名,三…

Linux 设备树文件手动编译的 shell 脚本

前言 前面通过 Makefile 实现手动编译 Linux 设备树 dts 源文件及其 设备树依赖 dtsi、.h 头文件,如何写成一个 shell 脚本,直接编译呢? 其实就是 把 Makefile 重新编写为 shell 脚本即可 编译设备树 shell 脚本 脚本内容如下&#xff1a…

【六一 iKun】Happy LiuYi, iKuns

六一了,放松下。 Python iKun from turtle import * screensize(1000,1000) speed(6)#把衣服画出来,从右肩膀开始#领子 penup() goto(-141,-179) pensize(3) fillcolor("black") pencolor("black") begin_fill() pendown() left(1)…

【Python实战】Python采集高校信息

前言 大家好,我们今天来爬取某站的高校名单,把其高校名单,成员和内容数获取下来,不过,我们发现这个网站比我们平时多了一个验证,下面看看我是怎么解决的。 环境使用 python 3.9pycharm模块使用 requests模块介绍 requests requests是一个很实用的Python HTTP客户端…

【线性dp必学四道题】线性dp四道经典例题【最长上升子序列】、【最长公共子序列】、【最长公共上升子序列(maxv的由来)】【最长公共子串】

【最长上升子序列】、【最长公共子序列】、【最长公共上升子序列】 最长上升子序列f[i] 表示以i结尾的最长子序列 最长公共子序列f[i][j] 表示 a前i 和 b前j个 最长公共长度 最长公共上升子序列f[i][j]代表所有a[1 ~ i]和b[1 ~ j]中以b[j]结尾的公共上升子序列的集合 最长公共子…

Spring Boot如何实现分布式追踪和监控

Spring Boot如何实现分布式追踪和监控 在分布式系统中,由于服务数量的增加和服务之间的相互调用,会出现跨服务的请求链路较长,难以追踪问题和定位性能瓶颈等问题。因此,分布式追踪和监控变得越来越重要。本文将介绍如何使用 Spri…

怎样一元钱部署自己的AI网站

前段时间我开发了一个简洁的AI问答网站,好多朋友感兴趣,因此我将网站代码在github上开源,并编写此教程,帮助大家快速部署自己的AI网站,会编程的朋友们也可在此基础上定制开发。 前提条件:有自己的ChatGPT账…

AI实战营:开源计算机视觉神器OpenMMLab

目录 OpenMMLab概述 OpenMMLab各开源算法库详细介绍 OpenMMLab开源生态 OpenMMLab概述 部署框架:MMdeploy 算法框架:MMPretrain预训练多模态、MMDetection目标检测、MMDetection3D目标检测、MMRotate旋转目标检测、MMSegmentation语义分割、MMPose姿…

操作系统_进程

操作系统_进程 1 冯•诺依曼体系结构2 操作系统(Operator System)2.1 设计OS的目的2.2 OS的定位 3 进程3.1 什么是进程?3.2 查看进程3.3 通过fork创建进程使用 if 进行分流如何杀死一个进程 3.4 进程状态R - 运行状态S - 浅睡眠状态D - 磁盘休…

Java中关于ConditionObject的signal()方法的分析

代码块的展示 isHeldExclusively()这个仅持有锁资源的方法,在ReentrantLock中重写进行判断,要是没有持有锁资源那么会返回false,就会出现直接抛异常IllegalMonitorStateException(非法监视器状态异常)获取排在Conditi…