Question

I'm trying to built a web-application which displays a dot on a map and update its position every 10seconds. The way I solved it right now is by polling a page via javascripts timeout every 10 seconds and parsing the result. This works fine, but when having multiple browsers polling the same webpage the webserver resources spike, obviously. Even when adding memcached as a intermediate.

My next thought was of instead polling the page with the latest positional information every 10 seconds, just create a open socket and send new data over it.

So after a search I stumbled upon socket.io which should do exactly what I want, but I'm not getting it to work.

Even a basic thing like the following doesn't work; it just show the hello world data in the console once. Instead of every second.... What is going wrong here?

server

var io = require('socket.io').listen(1332);
io.sockets.on('connection', function (socket) {

    setTimeout(function(){
        sentPosition(socket);
    }, 1000);
});

function sentPosition(socket){
    socket.emit('position', { 
            hello: 'world' 
        });
}

Browser

var socket = io.connect('http://myserver.com:8080');
socket.on('position', function (data) {
    console.log(data);
});
Was it helpful?

Solution

use javascript's setinterval method instead

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top