I have a object in the frontend and I want to broadcast it to all connected clients. Can I send it as a mere object, the way I defined it? Or do I always have to stringyfy it as JSON object before sending?
my object:
var myBox = {
x: 400,
y: 700,
w: 231,
h: 199,
c: "red",
....
}
do I need stringify?
var myBox = JSON.stringify({
x: 400,
y: 700,
...
});
At the moment I send it like this and the msg is a JSON:
socket.emit('message', msg);
I have a object in the frontend and I want to broadcast it to all connected clients. Can I send it as a mere object, the way I defined it? Or do I always have to stringyfy it as JSON object before sending?
my object:
var myBox = {
x: 400,
y: 700,
w: 231,
h: 199,
c: "red",
....
}
do I need stringify?
var myBox = JSON.stringify({
x: 400,
y: 700,
...
});
At the moment I send it like this and the msg is a JSON:
socket.emit('message', msg);
Share
Improve this question
edited May 16, 2013 at 18:24
poppel
asked May 16, 2013 at 16:34
poppelpoppel
1,5934 gold badges17 silver badges22 bronze badges
4
- 1 How are you "sending" it? – Explosion Pills Commented May 16, 2013 at 16:37
- Who knows... you didn't give us nearly enough information to help you. – Brad Commented May 16, 2013 at 16:37
- sorry I added some Infos. At the moment I send it like this: socket.emit('message', msg); – poppel Commented May 16, 2013 at 16:38
- 1 @poppel, Why not simply looking at the docs? socket.io/#how-to-use ... they have many examples where they pass objects as event's data. – plalx Commented May 16, 2013 at 16:50
3 Answers
Reset to default 14You can pass the object to emit
without stringifying it yourself. It will be sent as plaintext, but the client callback will be passed a parsed object.
In other words, doing this is fine:
var myBox = {
x: 400,
y: 700,
w: 231,
h: 199,
c: "red"
}
socket.emit('message', myBox);
When listening on the client, you don't need to worry about JSON.parse
:
socket.on('message', function (data) {
alert(data.x);
});
Yes, to send an object you will need to serialize it to a string (or ArrayBuffer, to be exact) - some sequence of bits to go over the wire (under the hood of HTTP/WS).
Yet, that serialisation does not necessarily need to be JSON.stringify
, it could be anything else as well.
From what I read in their docs, Socket.io has "automatic JSON encoding/decoding" so it will do call the JSON.stringify
for you, accepting plain objects as arguments to .emit
as well.
You can do a socket.emit with data from the object.
Like this:
socket.emit("message",{x:myBox.x,y:myBox.y, w:myBox.w, h:myBox.h, c:myBox.c});
or try:
socket.emit("message",myBox); //haven't tested it, but if it works, give plalx credit