系列文章目录
websocket训练地址:https://www.qiulianmao.com,正在搭建中
- 基础-websocket逆向
- 基础-http拦截
- 基础-websocket拦截
- 基础-base64编码与解码
- 基础-python实现protobuf序列化与反序列化
- 基础-前端js实现protobuf序列化与反序列化
- 视频号直播弹幕采集
- tiktok protobuf序列化与反序列化
- 实战一:Http轮询
- 更新中
前端js实现protobuf序列化与反序列化
1. 环境配置
node -v(显示版本则说明安装成功)
npm install -g require(对库文件的引用库)
npm install -g browserify(这个是用来打包成前端使用的js文件)
npm install google-protobuf(安装google库)
- 项目目录总览

2. 编写proto文件
新建case.proto文件
syntax = "proto3";
message Request{
repeated Headers Headers= 5;
string ContentEncoding = 6;
string ContentType = 7;
bytes Payload = 8;
}
message Headers{
string Key = 1;
string Value = 2;
}
3. 对proto文件进行编译
在cmd中执行
.\protoc --js_out=import_style=commonjs,binary:. case.proto
项目新建main.js文件
var MessageBody = require('./case_pb');
module.exports = {
DataProto: MessageBody
}
4. 生成前端可用的js文件
在cmd中执行,会借助main.js生成case.js,这个就可以直接在浏览器中使用了。
browserify main.js > case.js
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="case.js"></script>
</head>
<body>
<script>
let a = new proto.Request()
let b = new proto.Headers()
b.setKey('User-Agent')
b.setValue('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.46')
a.addHeaders(b)
let c = new proto.Headers()
c.setKey('Content')
c.setValue('gzip')
a.addHeaders(c)
a.setPayloadtype('utf-8')
console.log(a.toObject())
let d = a.serializeBinary()
console.log(d)
let e = new proto.Request.deserializeBinary(d)
console.log(e.toObject())
</script>
</body>
</html>
控制台查看结果

本文档详细介绍了如何在前端使用JavaScript实现Protocol Buffers (protobuf)的序列化和反序列化。首先,讲解了环境配置,包括下载protobuf 3.20版本并安装。接着,说明了如何编写.proto文件,然后通过特定命令进行编译。最后,展示了如何生成可在浏览器中使用的JS文件,并提供了前端使用的代码示例,通过控制台查看序列化和反序列化的结果。
1189

被折叠的 条评论
为什么被折叠?



