vue2、vue3中使用pb(Base64编码)

/proto/chat.proto 文件

ini 复制代码
syntax = "proto3";

// 定义Protobuf的包名称空间,通过指定包名来避免message名字冲突
package com.xxx.protobuf.model;

// 指定生成的Java类的包名。若不指定该选项,则会以头部声明中的package作为Java类的包名。
option java_package = "com.xxx.protobuf.model";
// 指定生成Java类的打包方式。不指定则默认false,表示所有的消息都作为内部类,打包到一个外部类中。true表示一个消息对应一个Java的POJO类
option java_multiple_files = false;
// 指定生成的外部类名
option java_outer_classname = "ChatProtos";

message Person {
  string name = 1;
  int32 id = 2;
  string email = 3;
}

message User {
  string name = 1;
  int32 id = 2;
  string email = 3;
}

/utils/protoParser.js 文件

typescript 复制代码
// src/utils/protoParser.js
import protobuf from 'protobufjs';

// vue2 import ChatProto from '@/proto/chat.proto';
// vue3 import ChatProto from '../proto/chat.proto?raw';

class ProtoParser {
  constructor() {
    this.root = null;
    this.loaded = false;
  }

  async init() {
    if (this.loaded) return;
    
    try {
      this.root = protobuf.parse(ChatProto, { keepCase: true }).root;
      this.loaded = true;
      console.log('Proto 文件加载成功');
    } catch (error) {
      console.error('Proto 文件解析失败:', error);
      throw error;
    }
  }

  async ensureInitialized() {
    if (!this.loaded) {
      await this.init();
    }
  }

  decodeMessage(type, msg) {
    try {
      let buffer;
      const binaryString = atob(msg);
      buffer = new Uint8Array(binaryString.length);
      for (let i = 0; i < binaryString.length; i++) {
          buffer[i] = binaryString.charCodeAt(i);
      }
      const MessageType = this.root.lookupType(`com.xxx.protobuf.model.${type}`);
      const message = MessageType.decode(buffer);
      const object = MessageType.toObject(message, {
        longs: String,
        enums: String,
        bytes: String,
        defaults: true,
        arrays: true,
        objects: true,
        oneofs: true
      });
      return object;
    } catch (error) {
      console.error(`解析消息类型 ${type} 失败:`, error,':msg:',msg);
      throw error;
    }
  }

  // 编码消息并返回字节数组
  async encodeMessage(type, object) {
    await this.ensureInitialized();
    
    try {
      const MessageType = this.root.lookupType(`com.xxx.protobuf.model.${type}`);
      
      // 验证对象
      const errMsg = MessageType.verify(object);
      if (errMsg) {
        console.warn(`验证消息 ${type} 失败:`, errMsg);
      }

      // 创建消息并编码
      const message = MessageType.create(object);
      const buffer = MessageType.encode(message).finish();
      return buffer;
    } catch (error) {
      console.error(`编码消息类型 ${type} 失败:`, error);
      throw error;
    }
  }

  // 编码消息并返回 base64 字符串(与安卓端格式一致)
  async encodeMessageToBase64(type, object) {
    await this.ensureInitialized();
    
    try {
      const buffer = await this.encodeMessage(type, object);
      return this.arrayBufferToBase64(buffer);
    } catch (error) {
      console.error(`编码消息为 Base64 失败:`, error);
      throw error;
    }
  }
  
  // ArrayBuffer 转 Base64
  arrayBufferToBase64(buffer) {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    for (let i = 0; i < bytes.byteLength; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
  }
  
  // Base64 转 ArrayBuffer
  base64ToArrayBuffer(base64) {
    const binaryString = atob(base64);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes;
  }
}

export default new ProtoParser();

安装protobufjs

css 复制代码
npm i protobufjs -D

配置

  1. vue.config.js
arduino 复制代码
chainWebpack: config => {
    ......
    // 添加对 .proto 文件的支持
    config.module
        .rule('proto')
        .test(/\.proto$/)
        .use('raw-loader')
        .loader('raw-loader')
        .end();
},
  1. vite.config.js
vbnet 复制代码
assetsInclude: ['**/*.proto'],

使用

csharp 复制代码
await protoParser.init(); //页面初始化时执行
// 确保 protoParser 已初始化
protoParser.ensureInitialized();
// 解析数据
const SpeakMsgRes = protoParser.decodeMessage('Person', res.data);
console.log('聊天消息:', SpeakMsgRes);
相关推荐
崔庆才丨静觅13 分钟前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊2 小时前
jwt介绍
前端
爱敲代码的小鱼2 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax