node.jssocket.ioraphael

display mouse pointer movement in other client computers using socket.io


I'm using socket.io engine to track the mouse pointer movement from the browser and send it to multiple web browsers. Here I get the x, y coordinates of the mouse pointer and then send it using socket.io engine.

socket.emit('mouse_position', {mx : x, my : y});

after that I get the relevant data from the application by following code

socket.on('mouse_position', function(data) {
    socket.broadcast.emit('mouse_position_update', data);
});

the I use a raphael object to show the mouse pointer in other browsers and use animate function to display the mouse pointer according to the parent mouse pointer movement.

var paper = new Raphael(canvas, 200, 200);
var cur = paper.circle(0, 0, 3);
cur.animate({
    cx : data.mx,
    cy : data.my
}, 1, 'linear');

the problem in this code is that if I lot of users (>100) log into this system , lot of bandwidth will be used and system may get crashed. can anybody tell me is there a better way to implement this system using socket.io engine or is there any algorithm we can use to solve the bandwidth issue. Any kind of help would be a great help for me .


Solution

  • You should decrease the amount of time you send you mouse coordinates. In your way every pixel your mouse is changed, your data is sent. (put console.log(1) in your callback and move your mouse for a few seconds).

    You can decrease the amount of time you send you data in the following way:

    var prevMouseX, prevMouseY;
    var intervalID = window.setInterval(function(){
       ... you get your mouse coordinates
    
       if (prevMouseX !== x || !prevMouseY !== y) {
          socket.emit('mouse_position', {mx : x, my : y});
       }
    }, 500);
    

    This way you will send your mouse coordinates every 0.5 seconds and only if they changed.