开发者

Why does my multiplayer javascript game slow down when another client (new tab) connects?

I'm trying to make a simple multiplayer game using canvas, socket.io and node.js. Everything's OK until another person connects (I open another tab and load the game there). When that happens, everything slows down and eventually stops (I can' move around).

How it works: When someone connects to the server, the server saves his socket in an array object and starts communication with the client. The client sends an object containing it's name and position and then the server goes trough that array of sockets and sends that to everyone else who is connected. When a client receives a message, it extracts the data, does something with it (like drawing based on the position) and then sets a timeout in 10ms to reply to the server with his position and name. This goes on and on and works well until I open a new windo开发者_如何学运维w/tab and reconnect, as I said.

Why does it slow down when I start another client? Here's the code:

server.js (this is just a piece of code, the rest is from the socket.io example)

io.sockets.on('connection', function (socket) {
     socket.emit('init', {id: names[players.length], level: 5});
     socket.on('got', function (data) { 
          console.log("got");
          players.push(new Player(socket));
          socket.emit('update', {msg: "ks"});
     });

     socket.on('update', function (data){
          for (i = 0; i < players.length; i++)
          {
               players[i].socket.emit('update', {msg: data});
          }
     });
});

Player = function(socket)
{
     this.socket = socket
}

game.js

self.socket.on('init', function (data) {
      self.pl = new self.Player(data.id, data.level);
      console.log(self.pl.id);
      self.defined = true;
      self.socket.emit('got', { my: "data" });
 });

 self.socket.on('update', function (data){
      self.pars(data);
          setTimeout(function(){self.socket.emit('update', {'pos': self.pl.pos, 'id': self.pl.id})}, 10);        
 });


My first thought is resource issues, I'm guessing this is all running on your local machine, you might just be eating up all the resources.

It could be anything from cpu to connections. Hard to say without more info.

Is your code leaving connection to the clients open the entire time time?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜