Socket.io is not emitting value

2019-06-04 16:32发布

问题:

I am having problem in receiving values emitted by socket.io, I am not getting where is the problem. Here am posting the code please help me to solve the problem.

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawnSync = require('child_process').spawnSync;

....

app.post('/loadImage',upload.any(),function(req, res) {
        fs.readFile('/home/pathtofile/file.json','utf8',function(err,data){
                if(err){
                    console.log(err);
                }else{
                    //console.log(data);
                    var precjson = JSON.parse(data);
                    var loaded_filename = precjson.Filename;
                    io.emit('emitfilename',{loaded_filename});
                }
            })
}
http.listen(8080,'0.0.0.0',function(){
    console.log('listening on 8080');
})

And here is my code where I am receiving the emitted values:

    <script type="text/javascript">
    var socket = io.connect('http://localhost:8080');

      socket.on('emitfilename',function(data){
        //console.log(data);
        var li = document.createElement('li');
        var filename = document.createElement('h4');

        filename.textContent = 'File Name:' + data.filename;
        li.appendChild(filename);

        document.getElementById('filenameoutput').appendChild(li);
     });
</script>

Instead of getting file name , I am getting undefined. Can any one please help me.

回答1:

You can't use "io" variable to emit data. You can use current socket of the client that just connected to send data :

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Or use io.sockets to emit to all sockets

io.sockets.emit('users_count', clients);

Hope it solve your problem ! Thanks !