简体   繁体   English

如何通过套接字io发送对象数组?

[英]How to send an array of objects through socket io?

I have been encountering a problem in sending array of object through socket io 我在通过套接字io发送对象数组时遇到问题

My server side code 我的服务器端代码

var addEntity = function(ent) {
    entityBag.push(ent);
};  
var entityBag = [];
addEntity(new Circle({
            x:  Math.random() * 5000,//(i%20) * space,
            y:  Math.random() * 5000,//Math.floor(i/20)*space,
            color: ['red', 'blue', 'green', 'yellow', 'purple', 'brown', 'violet'][Math.floor(Math.random()*7)],
            droplet: true  
        }));
socket.emit('updatePos',entityBag);

and my client side code 和我的客户端代码

var entityBag = [];
socket.on('updatePos', function(msg) {
    entityBag = msg;
});  

So my when I tried to debug the issue all the objects in the array were empty in the client side code. 因此,当我尝试调试问题时,客户端代码中数组中的所有对象均为空。 So I am probably guessing the error is with the socket 所以我大概猜错了套接字

please excuse my ignorance if the question is too trivial 如果这个问题太琐碎,请原谅我的无知

The Cirlce class Cirlce班

function Circle(attr) {
    attr = attr    
    var x = attr.x;
    var y = attr.y;
    var color = attr.color ;
    var borderColor = attr.borderColor || 'black';
    var droplet  = attr.droplet ;
}

I can't see your whole code so I can't find bugs in it but I tried to write something similar: 我看不到您的整个代码,因此找不到错误,但是我尝试编写类似的代码:

server.js: server.js:

'use strict';
const io = require('socket.io')(3000);
var entityBag = []; 
var someObject = {
            x:  Math.random() * 5000,//(i%20) * space,
            y:  Math.random() * 5000,//Math.floor(i/20)*space,
            color: ['red', 'blue', 'green', 'yellow', 'purple', 'brown', 'violet'][Math.floor(Math.random()*7)],
            droplet: true
} 
var anotherObject = {
            name: 'Utsav Mangal',
            color: ['red', 'blue', 'green', 'yellow', 'purple', 'brown', 'violet'],
            human: true,
            somekey: 'foo'
} 
var addEntity = function(ent) {
    entityBag.push(ent);
};             
addEntity(someObject);
addEntity(anotherObject);
io.on('connection', function (socket) {
    socket.emit('updatePos', entityBag);    
});
console.log('Plain socket.io server started at port 3000');

client.js client.js

'use strict';
const socket = require('socket.io-client')('http://localhost:3000');
socket.on('updatePos', function(data) {
    console.log(data);
});

You can try it with node server to start the server and node client to connect to it, everything works fine. 您可以在node server上尝试启动服务器,并通过node client连接到它,一切正常。 You don't have to JSON.stringify/parse, socket.io will do it for you. 您不必JSON.stringify / parse,socket.io会为您完成。 Your bug is somewhere else. 您的错误在其他地方。 Please show us the whole code. 请向我们展示整个代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM