Websoket using protocol Buffers3.0 transmission

Source: Internet
Author: User
Tags closure require

Protocol buffers is a data interchange format introduced by Google, which is smaller and faster than XML because it is binary-transmitted. 3.0 compared to 2.0 the change is relatively large. These changes can be seen in the official statement.

Using Protobuf.js to parse. Proto files on the front-end requires the introduction of Protobuf.js on the interface first. define a. Proto

Syntax = "Proto3";
Token
message mymodel{
    string UserID = 1;
    string Device = 3;
}
Message message{
    string channelid = 1;
    Bytes Content  = 4;
}
Load:
Protobuf.load ("Models.proto", function (err, root) {
    if (err)
        throw err;
      Console.log (root);
      var MyModel = Root.lookuptype ("MyModel");
      Console.log (MyModel);
});

Root contains the two models we have defined. The model can be used to send messages and parse messages. Notice that the content of our message above is the bytes type. JavaScript itself is not of this type.

According to Protobuf.js's official instructions can be achieved by Base64 code:

function Base64Encode (input) {
    var rv;
    RV = encodeURIComponent (input);
    RV = unescape (RV);
    RV = Window.btoa (RV);
    return RV;
}
var buffer1 = base64encode ("message");
    Console.log (buffer1);
    var model = {channelid: "12121", content:buffer1};
    var message = Message.create (model);//create
    var buffer = message.encode (message). Finish ();//turn into
    binary Console.log (buffer);

Run the page, the object has been transformed into an array

This time you can use the WebSocket send method to send objects to the backend, but can also be based on the protocol and the backend contract to do a second conversion. parsing:

  var Decodemodel = message.decode (buffer);
    Console.log (Decodemodel);
    Console.log (Ut8arraytostr (decodemodel.content));

Once we get the buffer, we'll convert to our object again.

This time we need to convert the Uint8array to a string in order to intuitively get the contents of our content.

function Ut8arraytostr (array) {var out, I, Len, C;

    var char2, Char3;
    out = "";
    len = Array.Length;
    i = 0;
        while (I < len) {c = array[i++]; Switch (c >> 4) {case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7://0XX
                XXXXX out + = String.fromCharCode (c);
            Break
                Case 12:case://110x xxxx 10xx xxxx char2 = array[i++]; Out + = String.fromCharCode (((C & 0x1F) << 6) |
                (Char2 & 0x3F));
            Break
                Case://1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++];
                CHAR3 = array[i++];
                               Out + = String.fromCharCode (((C & 0x0F) << 12) |
                               ((Char2 & 0x3F) << 6) |
                ((Char3 & 0x3F) << 0));
        Break }} RETurn out; }

This will complete the process. Summary:

The actual development is more complex than the one described above, first loaded. The Proto object is asynchronous, that is, when you use WebSocket to send a message, make sure that you have obtained the model, which is the message object in the example. The other one is compatibility processing. Protobuf.js compatibility is as follows:

For example, IE8 does not support, of course, we do not want to use the protobuf.js in IE8, because IE8 also does not support websocket, we can use polling. is to avoid introducing protobuf.js will be error, after all, this JS has a lot of new browser objects. You can use TypeOf to prevent it from running in an unsupported browser.

If you do not support websocket, you do not have to initialize the
if (!window. WebSocket) return;
if (typeof exports== "undefined") return;
        Exports.writefloatle = Writefloat_ieee754.bind (null, writeuintle);

In the same vein, their own JS to judge.

    function Loadproto () {
        if (typeof protobuf = = "undefined") return;//indicates that the browser failed to load
        protobuf.load (". /xx.proto ", function (err, root) {

This way, if you have an alternate polling communication, you can run it in IE8.

In addition, Google also provides a way for JavaScript to parse. proto files.

1. Commonjs-style imports (eg. ' var protos = require (' My-protos '); ')
2. Closure-style imports (eg. ' Goog.require (' My.package.MyProto ');

Closure-style need to rely on goog, a lot of, and Commonjs example more like on the node side, in this place around the day, unsuccessful, and finally chose the protobuf.js way.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.