sending a javascript object through websockets with faye
Asked Answered
J

5

45

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

the faye-websockets documentation says:

send(message) accepts either a String or a Buffer and sends a text or binary message over the connection to the other peer.

server side I'm using node and faye.

var WebSocket = require('faye-websocket');
var http = require('http');

var server = http.createServer();
server.addListener('upgrade', function(request, socket, head) {
    var ws = new WebSocket(request, socket, head);
    ws.send({topic:'handshake', data:'sdf487rgiuh7'});
});
server.listen(8000);

client side:

<script>
    var ws = new WebSocket('ws://localhost:8000');
    ws.onmessage = function(e) {
        console.log(e.data); //prints [Object object] string and not the object
    };
</script>

what is my error? Thanks

Jaclin answered 23/10, 2012 at 10:39 Comment(2)
who give -1 explains the reason please..Jaclin
The -1 is likely due to the fact that the error message has already told you exactly what is wrong.Haycock
S
105

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;

Sportswear answered 23/10, 2012 at 15:39 Comment(4)
Your link is dead :/ And there aren't any readme.md on the git repo of js-bson. Gonna search some doc.Protoxylem
Is it possible that the onmessage callback doesn't return the entire json string, and therefore JSON.parse throws a parsing error?Erudite
@MartinKonecny WebSockets is message based and messages are delivered in full (no partial messages). However, note that if you have something like websockify in the middle and you're actually talking to a regular TCP server on the other end, the message divisions are arbitrary (depend on TCP packet size, kernel window sizes, buffer sizes, etc). In that case you need to do some kind of re-assembly yourself.Sportswear
Thanks, I thought websockets were just plain sockets initiated via http. Good to know to is message based.Erudite
L
3

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);
Laureen answered 9/1, 2018 at 12:29 Comment(0)
P
3

add a function called json to the websocket object that transform in json and send the object passed by parameter

ws.json = (obj) => ws.send(JSON.stringify(obj));

ws.json({ message: "hello" });
Pedroza answered 23/10, 2022 at 22:54 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luckFrizzy
Z
2

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));
Zitazitah answered 23/10, 2012 at 11:0 Comment(4)
in your case you are sending a string but since faye supports sending binary data I want to exploit this featureJaclin
@Jaclin An JS object is no binary data, an image would be. So udidus answer is correct.Textualism
so the only method to serialize a js object is to stringify it?Jaclin
"Stringifying" an object is another way to say "serialize with JSON"Scissors
P
0

From the client side you can just send it via JSON.strigify and in the server side just do JSON.parse to get the data

Phelgon answered 12/6, 2023 at 5:52 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Chemotaxis

© 2022 - 2024 — McMap. All rights reserved.