javascript socket.io - JSON 是发送对象的必要条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16592908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:15:38  来源:igfitidea点击:

socket.io - is JSON a must to send an object

javascriptjsonnode.js

提问by poppel

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 对象?

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:

目前我像这样发送它并且 msg 是一个 JSON:

socket.emit('message', msg);

回答by Asad Saeeduddin

You can pass the object to emitwithout stringifying it yourself. It will be sent as plaintext, but the client callback will be passed a parsed object.

您可以将对象传递给 ,emit而无需自己对其进行字符串化。它将作为纯文本发送,但客户端回调将传递一个解析对象。

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);
});

回答by Bergi

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.stringifyfor you, accepting plain objects as arguments to .emitas well.

根据我在他们的文档中读到的内容,Socket.io 具有“自动 JSON 编码/解码”,因此它会JSON.stringify为您调用,并接受普通对象作为参数.emit

回答by Shazboticus S Shazbot

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