How to let JS automatically match proto Js
这次给大家带来让JS自动匹配出proto Js的方法,JS自动匹配出proto Js的方法的注意事项有哪些,下面就是实战案例,一起来看一下。
在与后端的WebSocket通信时,前端要带一个proto文件是一个累赘的事情。首先是明显的曝光了协议实体对象,再一个浏览器客户端很容易会缓存该文件,新的协议更新可能导致客户端不能使用,另外在cdn服务器上还需要配置.proto类型客户端才能下载过去。真是遗毒不浅,自己使用的时候会注意这些,但给别人使用的时候就很不乐观了,所以这次全部将proto文件转成JavaScript对象,省去协议文件和加载的步骤。
先看代码:
args = [].slice.call(arguments, 1 obj = ( i = 0; i < args.length; i++ p = key = i + 1 protobuf.Field(p[0], key, p[1] || "string" obj = ( i = 0; i < list.length; i++ ( protobuf == "undefined") ;= protobuf.Root().define("IMEntity""Token", ["UserID"], ["Token"], ["Device"], ["Version", "int32"], ["Appkey""Feedback", ["ResultCode", "int32"], ["ResultData"], ["Seq", "int32"], ["MsgID""ReceiptType", ["Receive", "Read" };
proto 主要有两种类型,Type和Enum。Type对应协议中的message,相当于是类。Enum就是枚举类型
var Root = protobuf.Root, Type = protobuf.Type, Field = protobuf.Field;var AwesomeMessage = new Type("AwesomeMessage").add(new Field("awesomeField", 1, "string"));var root = new Root().define("awesomepackage").add(AwesomeMessage);
枚举的创建不要需要Field。只需要add 字段名即可。那么接下来的问题是,手写root.add 也很烦,因为要一个一个对照属性,不断的复制粘贴,很容易出错。所以又做了个自动生成代码的页面:
<textarea id="content"> //登陆Token message Token{ string UserID = 1; //登陆接口返回的IMUserID string Token = 2; //登陆接口返回的Token string Device = 3; //客户端设备号 int32 Version = 4; //版本号,发布前与服务端约定值 string Appkey = 5; //客户端Appkey } //收到私信 message ReceivePrivateMessage{ string MsgID = 1; //消息id string SenderID = 2; //发送者id string ReceiverID = 3; //接收者id string Content = 4; //消息内容。客户端转换成业务相关的实体后,再做后续处理(客户端使用,服务器不做任何处理,原样下发) bool Ack = 5; //是否需要已读回执 int32 SendDateTime = 6; //消息发送时间 int32 ContentType = 7; //内容类型(客户端使用,服务器不做任何处理,原样下发) } //回执类型 enum ReceiptType{ Receive = 0; //已收回执(收到消息后立即发送给服务器的回执) Read = 1; //已读回执(用户进入消息阅读界面后发送给服务器的回执) } </textarea> <p id="result"></p> <script> function start() { $("#result").html(""); $("#result").append('root = new protobuf.Root().define("IMProtoEntity")<br>'); var reg = /("([^\\\"]*(\\.)?)*")|('([^\\\']*(\\.)?)*')|(\/{2,}.*?(\r|\n))|(\/\*(\n|.)*?\*\/)/g,// 过滤注释 str = $('#content').val(); // 欲处理的文本 // console.log(str.match(reg));// 打印出:匹配子串 var news = str.replace(reg, ""); // console.log(news); // 打印出:原文本 var reg1 = /[message|enum].*?{/mg; var regobj = /{[^}{]*?}/g;//新地址 var names = news.match(reg1); var protos = news.match(regobj); // console.log(names, protos); var root = {}; for (var i = 0; i < names.length; i++) { var rawname = names[i]; var rawObj = protos[i]; //if (~rawname.indexOf("message")) if (!rawObj) continue; var name = rawname.replace("{", '').replace("message ", '').replace("enum ", ''); var obj = { name: name }; if (~rawname.indexOf("enum")) { obj["type"] = "enum"; } rawObj = rawObj.replace("{", '').replace("}", ''); var protolist = rawObj.split(';'); // console.log("protolist", protolist); var plist = []; for (var j = 0; j < protolist.length; j++) { var p = $.trim(protolist[j]); if (p) { var args = []; var list = p.split(' '); // console.log("list", list); list.forEach(function (n) { n && args.push(n); }), // console.log("args", args); plist.push(args); } } obj.list = plist; console.log(obj); toProto(obj); } } start(); function toProto(obj) { var root = "root"; var fun = "createProto"; var enumfun = "createEnum"; var str = root + '.add('; var args; if (!obj.type) {//message args = ''; for (var i = 0; i < obj.list.length; i++) { var item = obj.list[i]; //老协议2.0 if (item[0] == "required" || item[0] == "optional") { item.shift(); } //新协议3.0 if (item[0] != "string") { args += '["' + item[1] + '","' + item[0] + '"]'; } else { args += '["' + item[1] + '"]'; } if (i < obj.list.length - 1) args += ","; } } else {//enum args = '['; for (var i = 0; i < obj.list.length; i++) { var item = obj.list[i]; args += '"' + item[0] + '"'; if (i < obj.list.length - 1) args += ","; } args += ']'; } var all = str + (obj.type ? enumfun : fun) + '("' + obj.name + '",' + args + '));'; // console.log(all); $("#result").append(all + "<br>"); } </script>
然后页面上会得到:
红色部分复制到工程里面就可以用了。当然要带上createProto和createEnum两个方法。proto的格式要规范,毕竟start里面是以空格split的。相对于protobuf.load("xx.proto",callback)的方式要好很多。load对位置要求比较死板,一定要在根目录。而且有类型不存在就会报错,终止程序。add方法不存在找不到类型的错误。另外速度也快了很多。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to let JS automatically match proto Js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

PHP String Matching Tips: Avoid Ambiguous Included Expressions In PHP development, string matching is a common task, usually used to find specific text content or to verify the format of input. However, sometimes we need to avoid using ambiguous inclusion expressions to ensure match accuracy. This article will introduce some techniques to avoid ambiguous inclusion expressions when doing string matching in PHP, and provide specific code examples. Use preg_match() function for exact matching In PHP, you can use preg_mat
