nodejs socket.io emit inside function loop

痞子三分冷 提交于 2019-12-11 03:20:11

问题


I would like to emit through socket.io inside a loop. For that I made a trigger which works well, but at each trig I call socket.emit and only the first emit works.

Here is the server code :

var server = require('http').createServer(handler);
var io = require('socket.io')(server);
var fs = require('fs');
var ee = require('events').EventEmitter;
var trig = new ee();

server.listen(8080);

function handler(req,res){
    fs.readFile('./index.html', 'utf-8', function(error, content) {
        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
        console.log('page affichée');
    }); 
}

io.on('connection',function(socket){
    socket.on('run',function(v){
        run(v);
    });
    trig.on('node',function(i){
        io.sockets.emit('node',i);
        console.log(i);
    });
});

function run(v){
    for(i=0;i<v;i++){
        trig.emit('node',i+1);
    }
}

and here is the client code :

<input id='file' type='text'></input>
<input type='button' value='lancer le process' onclick="socket.emit('run',document.getElementById('file').value);"></input>
<script>

        var compt_nod = document.getElementById('compteur_nodes');

        socket = io.connect('http://127.0.0.1:8080/');

        socket.on('node',function(v){
            compt_nod.value = v;
            console.log(v);
        });
</script>

I got the log from the server, but only the first answer on the client side. I'm quite new in JS and especialy in Node, so apologize for this maybe simple question.

来源:https://stackoverflow.com/questions/25309886/nodejs-socket-io-emit-inside-function-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!