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

这篇具有很好参考价值的文章主要介绍了微信小程序websocket使用protobuf,发送arraybuffer。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

前言

这是一次继前文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 用不起

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

cnpm install -g protobufjs@6.8.6

然后执行pbjs即可
微信小程序websocket使用protobuf,发送arraybuffer,微信小程序,websocket,小程序

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类

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

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);

})

四、小程序中的效果

微信小程序websocket使用protobuf,发送arraybuffer,微信小程序,websocket,小程序
微信小程序websocket使用protobuf,发送arraybuffer,微信小程序,websocket,小程序文章来源地址https://www.toymoban.com/news/detail-617155.html

到了这里,关于微信小程序websocket使用protobuf,发送arraybuffer的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • uniapp vue3 微信小程序 项目中使用 websocet、微信小程序真机调试 websocket 报错 errMsg: “Invalid HTTP status.“

    uniapp-websocket官方文档 注意点:需要在确定建立连接后才能去发送数据 这个错误通常是因为小程序 WebSocket 请求的地址没有配置为 HTTPS,而是使用了 HTTP,因此需要注意以下几点: 小程序开发者工具可以支持使用 ws:// 前缀的 WebSocket 地址,但在真机上会因为不安全的原因而无

    2024年01月17日
    浏览(49)
  • 【微信小程序】使用 WebSocket 进行订阅操作、连接监听、接收到服务器的消息事件

    在微信小程序中使用 WebSocket 进行订阅操作,可以通过 wx.connectSocket 方法创建 WebSocket 连接,并通过相关事件处理函数进行订阅和数据处理。 以下是一个示例代码,演示了在微信小程序中使用 WebSocket 进行订阅: 在上述代码中,我们首先使用 wx.connectSocket 方法创建 WebSocket 连接

    2024年02月16日
    浏览(40)
  • 【微信小程序】使用 wx.request 方法来发送POST网络请求,携带RequestBody参数

    在微信小程序中,你可以使用 wx.request 方法来发送网络请求。以下是将上述 Java 代码转换为微信小程序版本的示例: 在上述代码中,我们使用 wx.request 方法发送 POST 请求,并将请求的 URL、请求体数据、请求头等信息进行相应的设置。请求成功后,会在回调函数的 success 中处

    2024年02月15日
    浏览(36)
  • 微信小程序如何使用原生Websocket api与Asp.Net Core SignalR 通信

    如题,这可能算是.net 做小程序的服务端时,绕不开的一个问题,老生常谈了。同样的问题,我记得我2018/19年的一个项目的解决方案是: 修改官方的SignalR.js的客户端 :把里面用到浏览器的Websocket改成微信小程序的官方api的。目前网上也有不少这样的方案,已经改好开源了;

    2024年02月09日
    浏览(65)
  • 微信小程序 -- 微信小程序发送红包

    参考链接:微信小程序 – 微信小程序发送红包 组织参数 点击查看微信的文档 发送示例 拼接参数(ASCII码从小到大排序(字典序)) 加密参数 将参数实体转换成xml格式 最后就是发送请求 相信发送post请求大家都不陌生了吧 最后就是对微信返回的参数进行解析,建议遇到问

    2024年02月10日
    浏览(32)
  • 【微信小程序】使用WxNotificationCenter实现复杂的事件通信功能,在任意页面中订阅事件、发送事件和取消订阅事件

    在微信小程序中,如果需要实现复杂的事件通信功能,可以使用第三方库来辅助实现。以下是一些常用的第三方库示例: WxNotificationCenter Github地址(https://github.com/icindy/WxNotificationCenter) WxNotificationCenter是一个基于发布/订阅模式的事件通知库,可以在微信小程序中实现跨页面

    2024年02月16日
    浏览(30)
  • 微信小程序全局websocket

    全篇干货无废话 实现微信小程序全局websocket 含掉线重连,心跳保活等机制,可做参考示例 app.js

    2024年02月09日
    浏览(35)
  • 微信小程序实现发送短信的功能(发送短信)

    我使用的是微信小程序的云开发这种方式来实现的,纯前端操作,无需后端接入。 1,打开微信公众平台中的【云开发】  2,在概览里面点击开通静态网站  3,点击开通  4,确定开通,这地方看上去是要收费的,但是第一个月是有免费的额度给你使用的,后期收不收费要通

    2024年02月09日
    浏览(34)
  • 微信小程序:发送小程序订阅消息

    文档:小程序订阅消息(用户通过弹窗订阅)开发指南 在微信公众平台(https://mp.weixin.qq.com)手动配置获取模板 ID 2.1、获取消息下发权限 文档:一次性订阅消息、长期订阅消息 示例代码 这里需要注意一个坑,如果用户未授权,需要引导用户打开设置手动设置 2.2、获取登录凭

    2024年01月25日
    浏览(29)
  • 微信小程序发送消息推送

    在小程序开发中,如果想实现:用户发给小程序的消息以及开发者需要的事件推送,在小程序项目中,我们想要实现这样一个功能, 比如我们小程序中的客服功能,我不想要使用小程序后台的在线客服功能,但我又想实现客服功能,这个时候微信提供了消息推送功能,在小程序

    2024年02月09日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包