nodejs socket.io emit inside function loop

2019-07-21 03:58发布

问题:

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.