Socket.io - Is JSON A Must To Send An Object
Solution 1:
You 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);
});
Solution 2:
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.
Solution 3:
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
Post a Comment for "Socket.io - Is JSON A Must To Send An Object"