Node Socket.io对象麻烦 [英] Node Socket.io object trouble

查看:72
本文介绍了Node Socket.io对象麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Node Socket.IO时遇到了一些麻烦



我把所有代码都放在了pastebins中



服务器文件

  var io = require(socket.io)。listen(1337); 

io.set(log level,0);

var particles = [];
var players = [];
var remove_loop;
var particle;



io.sockets.on(connection,function(socket){

// connection
socket.emit( 你好);
console.log(已建立新连接);

//新玩家
socket.on(new_player,function() {
players.push(socket.id);
console.log(New player connected。);
console.log(ID:+ socket.id);
});

//新粒子
socket.on(new_particle,函数(数据){
粒子=数据;
socket.broadcast。 emit(particles_data,particle);
});

});

游戏文件

  window.onload = function(){

var canvas = document.getElementById(canvas);
var ctx = canvas.getContext(2d);

//显示设置
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

setInterval(function(){
if(canvas.width!= window.innerWidth || canvas.height!= window.innerHeight){
canvas.width = window。 innerWidth;
canvas.height = window.innerHeight;
}
},1000);

//删除游标
document.getElementById(canvas)。style.cursor =none;

//服务器连接
var socket = io.connect(http:// localhost:1337);


//变量
var update_loop;
var draw_loop;
var local_player;
var mouse_x;
var mouse_y;
var remote_players;
var粒子;
var remove_loop;
var爆炸;
var background_color;


init();
函数init(){
//初始化

local_player = new Player();
background_color =000000;
explosion = true;
remote_players = [];
粒子= [];

draw_loop = setInterval(function(){draw();},10);
update_loop = setInterval(function(){update();},10);

//服务器
socket.on(hello,function(){
socket.emit(new_player);
});

socket.on(particles_data,function(data){
particles.push(data);
});

};


函数update(){

for(var i = 0; i< particles.length; i ++){
particles [i] 。移动();
}

};


function draw(){
// background_color
ctx.fillStyle =#+ background_color;
ctx.fillRect(0,0,canvas.width,canvas.height);

//删除粒子
setInterval(function(){
if(!remove_loop)remove_loop = setInterval(function(){
setTimeout(function(){
if(particles.length> 0){
particles.shift();
}
},1);
},20);
},10);

//粒子
for(var i = 0; i< particles.length; i ++){
if(particles [i] .x< canvas.width& ;&
粒子[i] .y< canvas.width){
if(粒子[i] .x< canvas.width&&
粒子[i]。 y< canvas.height){
particles [i] .draw(ctx);
}
}
}

}

函数newParticle(){
socket.emit(new_particle,new粒子(local_player.x,local_player.y,local_player.color));
particles.push(new Particle(local_player.x,local_player.y,local_player.color));
};

//移动鼠标
canvas.onmousemove = function(event){
if(!event)event = window.event;
local_player.x = event.pageX;
local_player.y = event.pageY;

newParticle();
};

//触摸鼠标(手机/桌子)
canvas.onmousedown = function(event){
if(!event)event = window.event;
local_player.x = event.pageX;
local_player.y = event.pageY;

newParticle();
}

};

播放器文件

  function Player(){
this.x = 0;
this.y = 0;
this.color = Math.floor(Math.random()* 999999);
while(this.color< 100000){
this.color = Math.floor(Math.random()* 999999);
}
};

粒子文件

  function Particle(x,y,color){
this.start_x = x;
this.start_y = y;
this.speed = Math.floor(Math.random()* 3 + 1);
this.x = x;
this.y = y;
this.size = Math.floor(Math.random()* 3 + 1);
this.color =#+ color;
this.direction = Math.floor(Math.random()* 8);
this.move = function(){
this.speedDecreaseChance = Math.random(Math.random()* 100);
//粒子失去速度的机会就像你用
//看到真实粒子
if(this.speedDecreaseChance> 3){this.speed - = 0.5};
//从X和Y移动-AWAY-非常重要。
this.subDirection = Math.floor(Math.random()* 2);
if(this.direction == 0){//左上角
if(this.subDirection == 0){
this.x - = this.speed;
} else if(this.subDirection == 1){
this.y - = this.speed;
}
}否则if(this.direction == 1){//右下角
if(this.subDirection == 0){
this.x + = this。速度;
} else if(this.subDirection == 1){
this.y + = this.speed;
}
}否则if(this.direction == 2){//右上角
if(this.subDirection == 0){
this.x + = this。速度;
} else if(this.subDirection == 1){
this.y - = this.speed;
}
}否则如果(this.direction == 3){//左下角
if(this.subDirection == 0){
this.x - = this。速度;
} else if(this.subDirection == 1){
this.y + = this.speed;
}
}否则if(this.direction == 4){// left
this.x - = this.speed / 1.5;
if(this.subDirection == 0){
this.y - = this.speed;
} else if(this.subDirection == 1){
this.y + = this.speed;
}
}否则if(this.direction == 5){// up
this.y - = this.speed / 1.5;
if(this.subDirection == 0){
this.x - = this.speed;
} else if(this.subDirection == 1){
this.x + = this.speed;
}
}否则if(this.direction == 6){// right
this.x + = this.speed / 1.5;
if(this.subDirection == 0){
this.y - = this.speed;
} else if(this.subDirection == 1){
this.y + = this.speed;
}
}否则if(this.direction == 7){// down
this.y + = this.speed / 1.5;
if(this.subDirection == 0){
this.x - = this.speed;
} else if(this.subDirection == 1){
this.x + = this.speed;
}
}
};
this.draw = function(ctx){
ctx.beginPath();
ctx.shadowColor = this.color;
ctx.shadowBlur = 8;
ctx.arc(this.x,this.y,this.size,0,2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
ctx.shadowBlur = 0;
};
};

现在问题是服务器和所有套接字之间的流量出错了。
我想要做的是当有一个粒子对象将它们发送到服务器并且服务器将它们发送给除原始发件人之外的所有人时。



<我是通过socket.broadcast.emit()做到的;
这成功了。



然而,当对象到达其他套接字时,我收到此错误:

 未捕获的TypeError:对象#<对象>没有方法'move'
Uncaught TypeError:Object#< Object>没有方法'draw'

对于那时存在的每个粒子对象。
如果有人知道为什么我的对象会失去他们的方法并且会非常友好地帮助遇险的程序员我会非常高兴:)



提前致谢!

解决方案

据我所知,Socket.IO期望JSON数据作为emit函数的第二个参数。根据 http://www.json.org/ ,JSON数据格式不支持作为值的功能



您正在发送一个javascript对象,并期望从另一个客户端上的json创建该对象。这不是Socket.IO通信的工作方式。



您应该发送构造对象所需的数据,并使用它来构造客户端上的对象。



您可以做以下事情



更改此行

  socket.emit(new_particle,new Particle(local_player.x,local_player.y,local_player.color)); 

  socket.emit(new_particle,{x:local_player.x,y:local_player.y,color:local_player.color}); 

然后是事件监听器

  socket.on(particles_data,function(data){
particles.push(data);
});

处理从数据创建对象

  socket.on(particles_data,function(data){
particles.push(new Particle(data.x,data.y,data.color));
});


I'm having some trouble with Node Socket.IO

I have put all my code in pastebins

Server file

var io = require("socket.io").listen(1337);

io.set("log level", "0");

var particles = [];
var players = [];
var remove_loop;
var particle;



io.sockets.on("connection", function(socket) {

    //connection
    socket.emit("hello");
    console.log("A new connection has been established");

    //new player
    socket.on("new_player", function() {
        players.push(socket.id);
        console.log("New player connected.");
        console.log("ID: " + socket.id);
    });

    //new particle
    socket.on("new_particle", function(data) {
        particle = data;
        socket.broadcast.emit("particles_data", particle);
    });

});

Game file

window.onload = function() {

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    //display settings
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    setInterval(function() {
        if(canvas.width != window.innerWidth || canvas.height != window.innerHeight) {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        }
    }, 1000);

    //remove cursor
    document.getElementById("canvas").style.cursor = "none";

    //server connection
    var socket = io.connect("http://localhost:1337");


    //variables
    var update_loop;
    var draw_loop;
    var local_player;
    var mouse_x;
    var mouse_y;
    var remote_players;
    var particles;
    var remove_loop;
    var explosion;
    var background_color;


    init();
    function init() {
        //initialize

        local_player = new Player();
        background_color = "000000";
        explosion = true;
        remote_players = [];
        particles = [];

        draw_loop = setInterval(function() { draw(); }, 10);
        update_loop = setInterval(function() { update(); }, 10);

        //server
        socket.on("hello", function() {
            socket.emit("new_player");
        });

        socket.on("particles_data", function(data) {
            particles.push(data);
        });

    };


    function update() {

        for(var i = 0; i < particles.length; i++) {
            particles[i].move();
        }

    };


    function draw() {
        //background_color
        ctx.fillStyle = "#" + background_color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        //remove particles
        setInterval(function() {
        if(!remove_loop) remove_loop = setInterval(function() {
                setTimeout(function() {
                    if(particles.length > 0) {
                        particles.shift();
                    }
                }, 1); 
            }, 20);
    }, 10);

        //particles
        for(var i = 0; i < particles.length; i++) {
            if(particles[i].x < canvas.width &&
                particles[i].y < canvas.width) {
                if(particles[i].x < canvas.width &&
                    particles[i].y < canvas.height) { 
                    particles[i].draw(ctx);
                }
            }
        }

    }

    function newParticle() {
        socket.emit("new_particle", new Particle(local_player.x, local_player.y, local_player.color));
        particles.push(new Particle(local_player.x, local_player.y, local_player.color));
    };

    //move mouse
    canvas.onmousemove = function(event) {
        if(!event) event = window.event;
        local_player.x = event.pageX;
        local_player.y = event.pageY;

        newParticle();
    };

    //touch mouse (phones/tables)
    canvas.onmousedown = function(event) {
        if(!event) event = window.event;
        local_player.x = event.pageX;
        local_player.y = event.pageY;

        newParticle();
    }

};

Player file

function Player() {
    this.x = 0;
    this.y = 0;
    this.color = Math.floor(Math.random() * 999999);
    while (this.color < 100000) {
        this.color = Math.floor(Math.random() * 999999);
    }
};

Particle file

function Particle(x, y, color) {
    this.start_x = x;
    this.start_y = y;
    this.speed = Math.floor(Math.random() * 3 + 1);
    this.x = x;
    this.y = y;
    this.size = Math.floor(Math.random() * 3 + 1);
    this.color = "#" + color;
    this.direction = Math.floor(Math.random() * 8);
    this.move = function() {
        this.speedDecreaseChance = Math.random(Math.random() * 100);
        //Chance that the particle loses it's velocity like you would
        //see with real particles
        if(this.speedDecreaseChance > 3) { this.speed -= 0.5 };
        //It's important that they move -AWAY- from X and Y.
        this.subDirection = Math.floor(Math.random() * 2);
        if(this.direction == 0) { //upper left
            if(this.subDirection == 0) {
                this.x -= this.speed;
            } else if(this.subDirection == 1) {
                this.y -= this.speed;
            } 
        } else if(this.direction == 1) { //bottom right
            if(this.subDirection == 0) {
                this.x += this.speed;
            } else if(this.subDirection == 1) {
                this.y += this.speed;
            }
        } else if(this.direction == 2) { //upper right
            if(this.subDirection == 0) {
                this.x += this.speed;
            } else if(this.subDirection == 1) {
                this.y -= this.speed;
            } 
        } else if(this.direction == 3) { //bottom left
            if(this.subDirection == 0) {
                this.x -= this.speed;
            } else if(this.subDirection == 1) {
                this.y += this.speed;
            }
        } else if(this.direction == 4) { //left
            this.x -= this.speed/1.5;
            if(this.subDirection == 0) {
                this.y -= this.speed;
            } else if(this.subDirection == 1) {
                this.y += this.speed;
            }
        } else if(this.direction == 5) { //up
            this.y -= this.speed/1.5;
            if(this.subDirection == 0) {
                this.x -= this.speed;
            } else if(this.subDirection == 1) {
                this.x += this.speed;
            }
        } else if(this.direction == 6) { //right
            this.x += this.speed/1.5;
            if(this.subDirection == 0) {
                this.y -= this.speed;
            } else if(this.subDirection == 1) {
                this.y += this.speed;
            }
        } else if(this.direction == 7) { //down
            this.y += this.speed/1.5;
            if(this.subDirection == 0) {
                this.x -= this.speed;
            } else if(this.subDirection == 1) {
                this.x += this.speed;
            }
        }
    };
    this.draw = function(ctx) {
        ctx.beginPath();
        ctx.shadowColor = this.color;
        ctx.shadowBlur = 8;
        ctx.arc(this.x, this.y, this.size ,0 ,2*Math.PI);
        ctx.fillStyle = this.color;
            ctx.fill();
        ctx.shadowBlur = 0;
    };
};

Now the problem is that there's an error in my traffic between the server and all sockets. What I want to do is make it possible that when one has particle objects to send them to the server and the server sends them to everyone except the original sender.

I did this through socket.broadcast.emit(); This went successful.

However when the objects arrive at the other sockets I get this error:

Uncaught TypeError: Object #<Object> has no method 'move'
Uncaught TypeError: Object #<Object> has no method 'draw' 

For every particle object that exists at that moment. If anyone knows why my objects lose their methods and would be so friendly to help a programmer in distress I'd be absolutely delighted :)

Thanks in advance!

解决方案

From what I know Socket.IO expected JSON data as 2nd parameter for the emit function. JSON data format doesn't support function as values according to http://www.json.org/

You are sending a javascript object and expecting the object to be created from the json on a different client. This is not how Socket.IO communication works.

Instead of doing that you should send the data required to construct the object and use that to construct the object on the client.

You could do some thing like the following

Change this line

socket.emit("new_particle", new Particle(local_player.x, local_player.y, local_player.color));

to

socket.emit("new_particle", {x:local_player.x, y:local_player.y, color:local_player.color});

and then the event listener

socket.on("particles_data", function(data) {
  particles.push(data);
});

to handle the creation of object from the data

socket.on("particles_data", function(data) {
  particles.push(new Particle(data.x, data.y, data.color));
});

这篇关于Node Socket.io对象麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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