sending a javascript object through websockets with faye

后端 未结 3 432
闹比i
闹比i 2020-12-12 22:12

Hi all I\'m trying to send a javascript object through websockets:

the faye-websockets documentation says:

send(message) accepts either

相关标签:
3条回答
  • 2020-12-12 22:57

    Client:

    const bson = new BSON();
    ws.binaryType = 'arraybuffer';
    
    ws.onmessage = function(event) {
      console.log(bson.deserialize(Buffer.from(event.data)));
    }
    

    Server:

     const data = bson.serialize({ ... });
     ws.send(data);
    
    0 讨论(0)
  • 2020-12-12 23:00

    I'm basically working with Socket.IO, but it looks like you need to stringify your data in the server and parse it in the client like so:

    in the server:

    ws.send(JSON.stringify({topic:'handshake', data:'sdf487rgiuh7'}));
    

    in the client:

    console.log(JSON.parse(e.data));
    
    0 讨论(0)
  • 2020-12-12 23:03

    WebSockets support sending and receiving: strings, typed arrays (ArrayBuffer) and Blobs. Javascript objects must be serialized to one of the above types before sending.

    To send an object as a string you can use the builtin JSON support:

    ws.send(JSON.stringify(object));
    

    To send an object as a typed array you can use a javascript BSON library such as this one:

    ws.send(BSON.serialize(object));
    

    When you receive a WebSocket message you will need to deserialize it.

    To deserialize a JSON string from a WebSocket message:

    ws.onmessage = function (e) {
        var object = JSON.parse(e.data);
        ...
    };
    

    If you are using binary messages over WebSocket, then first you should set the binaryType attribute in order to receive all binary messages as typed arrays:

    ws.binaryType = "arraybuffer";
    

    Then the deserialization will look like this:

    ws.onmessage = function (e) {
        var object = BSON.deserialize(e.data);
        ...
    };
    

    Here is a blog post about using BSON in Javascript;

    0 讨论(0)
提交回复
热议问题