Detailed explanation of downloading and using protobuf.js
Because ProtoBuf's serialization efficiency and size are very good, it is used more and more in network communications; and webosocket is becoming more and more widely used as web3.0, and the combination of the two Together they will gradually form a trend; I wanted to test a C# websocket I wrote, so I also wrote a js example on the web combined with pb:
1. First download protobuf.js
2. Introduce protobuf related js files
3. Create proto file
1 package wenlipackage;2 syntax = "proto3";3 4 message WSMessage { 5 required string id = 1;6 required string content = 2;7 required string sender = 3;8 required string time = 4;9 }
The protobuf format type of js is
Field type | Expected JS type (create, encode) | Conversion (fromObject) |
---|---|---|
s-/u-/int32 s-/fixed32 |
number (32 bit integer) |
value | 0 if signedvalue >>> 0 if unsigned |
s-/u-/ int64 s-/fixed64 |
Long -like (optimal)number (53 bit integer) |
Long.fromValue(value) with long.jsparseInt(value, 10) otherwise |
double |
number
|
Number(value)
|
boolean |
| Boolean(value)
|
string |
| String(value)
|
Uint8Array | (optimal) Buffer(optimal under node) Array.(8 bit integers)
| base64.decode(value) if a string Objectwith non-zero .length is assumed to be buffer-like
|
number | (32 bit integer) Looks up the numeric id if a | string
|
Valid message | Message.fromObject(value) |
|
1 <script type="text/javascript">
2 var WSMessage;
3 var wsmessage;
4 var buffer;
5 protobuf.load("/proto/Message.proto", function (err, root) {
6 if (err) throw err;
7 WSMessage = root.lookup("wenlipackage.WSMessage");
8 wsmessage = WSMessage.create({ id: "1", content: "hello", sender: "web", time: new Date().getTime() });
9 buffer = WSMessage.encode(wsmessage).finish();
10 });
11 </script>
WSMessage是一个解码编码器
wsmessage是具体的某个定义的proto实例 是一个8位无符号的字节数组
1 <script type="text/javascript"> 2 var wsUri = "ws://127.0.0.1:8082/"; 3 var output; 4 function init() { 5 output = document.getElementById("output"); 6
testWebSocket(); 7 } 8 function testWebSocket() { 9 websocket = new WebSocket(wsUri);10 websocket.onopen = function (evt) {11 onOpen(evt)12 };
websocket.onclose = function (evt) {14 onClose(evt)15 };16 websocket.onmessage = function (evt) {17 onMessage(evt)18 };19
websocket.onerror = function (evt) {20 onError(evt)21 };22 }23 function onOpen(evt) {24 writeToScreen("CONNECTED");25 doSend(buffer);
}27 function onClose(evt) {28 writeToScreen("DISCONNECTED");29 }30 function onMessage(evt) {31 var reader = new FileReader();32 reader.readAsArrayBuffer(evt.data);
reader.onload = function (e) {34 var buf = new Uint8Array(reader.result);35 writeToScreen('<span style="color: blue;">RESPONSE: ' + WSMessage.decode(buf).content + '</span>');36 }37 }38
function onError(evt) {39 writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);40 }41 function doSend(message) {42 writeToScreen("SENT: " + wsmessage.content);43
websocket.send(buffer);44 }45 function writeToScreen(message) {46 var pre = document.createElement("p");47 pre.style.wordWrap = "break-word";48
pre.innerHTML = message;49
output.appendChild(pre);50 }51 window.addEventListener("load", init, false);52 </script>
6. Interoperability test
The above is the detailed content of Detailed explanation of downloading and using protobuf.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

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

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

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

Golang is a powerful programming language, and its use in WebSocket programming is increasingly valued by developers. WebSocket is a TCP-based protocol that allows two-way communication between client and server. In this article, we will introduce how to use Golang to write an efficient WebSocket server that handles multiple concurrent connections at the same time. Before introducing the techniques, let's first learn what WebSocket is. Introduction to WebSocketWeb
