[英]socket.io - is JSON a must to send an object
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? 或者我总是必须在发送之前将其作为JSON对象进行stringyfy?
my object: 我的目标:
var myBox = {
x: 400,
y: 700,
w: 231,
h: 199,
c: "red",
....
}
do I need stringify? 我需要stringify吗?
var myBox = JSON.stringify({
x: 400,
y: 700,
...
});
At the moment I send it like this and the msg is a JSON: 目前我发送它像这样,msg是一个JSON:
socket.emit('message', msg);
You can pass the object to emit
without stringifying it yourself. 您可以将对象传递给emit
而不用自己进行字符串化。 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
: 在客户端上侦听时,您不必担心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). 是的,要发送一个对象,你需要将它序列化为一个字符串(或者确切地说就是ArrayBuffer) - 一些比特序列通过线路(在HTTP / WS的引擎盖下)。
Yet, that serialisation does not necessarily need to be JSON.stringify
, it could be anything else as well. 然而,该序列化不一定需要是JSON.stringify
,它也可能是其他任何东西。
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. 根据我在他们的文档中读到的内容 ,Socket.io具有“ 自动JSON编码/解码 ”,因此它将为您调用JSON.stringify
,同时接受普通对象作为.emit
参数。
You can do a socket.emit with data from the object. 您可以使用来自对象的数据执行socket.emit。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.