vue中使用protobuf教程

1,116 阅读1分钟

1.在准备前需要让vue环境支持加载.proto文件,安装protobufjs、file-loader依赖,然后在vue.config.js中编写webpack的配置:

npm install protobufjs file-loader
chainWebpack: config => {
    config.module
      .rule('protobuf')
      .test(/\.proto$/)
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: '[name].[ext]',
        outputPath: 'proto/',
      })
      .end();
  },

2.配置在src目录下创建proto文件夹,在proto文件夹下创建以.proto结尾的文件,并写入一下内容定义字段

image.png

syntax = "proto3"; //标记当前为proto3版本
package allProto;  //定义当前proto文件名为allProto

 //定义字段规则
message HttpUserInfo{
  string userName = 1;
  string userGuid = 2;
  int32 type  = 3;
}

3.在终端中使用npm安装protobuf

npm install protobuf

4.在组件中引入protobufjs 和 创建的proto文件

image.png

5.发送数据

loadProtoFile() {
      return new Promise((resolve, reject) => {
      //这里的protobuf就是protobufjs的实例对象
      //这里的protoFile就是上面引入的proto文件
        protobuf.load(protoFile, (err, root) => {
          if (err) {
            return
          }
          // 这里的allProto就是proto文件中跟在packge后面的名称,HttpUserInfo为其中的一个message
          const UserInfoRequest = root.lookupType('allProto.HttpUserInfo')

          // Exemplary payload
          //设置传递的参数
          const payload = { 
            userName: 'long',
            userGuid: 'aaa',
            type: 1,
          }

          // Verify the payload if necessary (i.e. when possibly incomplete or invalid)
          const errMsg = UserInfoRequest.verify(payload)
          if (errMsg) {
            console.error(errMsg)
            return
          }
          
          var message = UserInfoRequest.create(payload)
          // Encode a message to an Uint8Array (browser) or Buffer (node)
          var messageBuffer = UserInfoRequest.encode(message).finish()
          resolve(messageBuffer)
          reject(err)
        })
      })
    },

使用loadProtoFile.then即可获取到可发送的数据格式。

注意:以上整个操作其实可以理解为JS中使用的json.stringfy(payload)

6.接收数据

image.png

const data = response.data;//将获取到的响应数据赋值给data
loadProtoFile() {
    return new Promise((resolve, reject) => {
        //protoFile为引入的protoFile文件
        protobuf.load(protoFile, (err, root) => {
            const UserInfoResponse = root.lookupType('ccprotos.VerifyCodeMessage')
            var message = UserInfoResponse.decode(new Uint8Array(data))
            var object = UserInfoResponse.toObject(message, {
                longs: String,
                enums: String,
                bytes: String,
            })
            resolve(object)
            reject(err)
        })
    })
},

注意:以上整个操作可以理解为json.parse(data)