socket.io-发送对象必须是JSON [英] socket.io - is JSON a must to send an object

查看:672
本文介绍了socket.io-发送对象必须是JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在前端有一个对象,我想将其广播给所有连接的客户端.我可以按照定义的方式将其作为单纯的对象发送吗?还是在发送之前始终必须将其作为JSON对象进行字符串化处理?

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?

我的对象

var myBox = {
         x: 400,
         y: 700,
         w: 231,
         h: 199,
         c: "red",
         ....
         }

我需要字符串化吗?

var myBox  = JSON.stringify({

            x: 400,
            y: 700,
            ...
        });

此刻,我像这样发送它,而味精是一个JSON:

At the moment I send it like this and the msg is a JSON:

socket.emit('message', msg);

推荐答案

您可以将对象传递给emit而不自己对其进行字符串化.它将以纯文本形式发送,但客户端回调将传递给已解析的对象.

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

在客户端上侦听时,您无需担心JSON.parse:

When listening on the client, you don't need to worry about JSON.parse:

socket.on('message', function (data) {
    alert(data.x);
});

这篇关于socket.io-发送对象必须是JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆