Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

node.js - sending a javascript object through websockets with faye

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...