简体   繁体   中英

socket.io not working node.js

I am not able to run socket.io code in node.js, console.log() is also not displaying when running the code. Below is the code.

app.js

var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 3000);
app.post('/testStream',test.testStream);
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

module.exports.appServer = server;

and I have created a test.js file where I am accessing this exported variable appServer.

var server = require('../app.js');

exports.testStream = function(req,res){        
    var io = require('socket.io').listen(server.appServer);
    io.on('connection',function(socket){
        console.log("in socket");
        fs.readFile('E:/temp/testimg.png',function(err,buf){
            socket.emit('image',{image: true,buffer: buf});
            console.log("test image");
        });
    })       
}

when the code runs it stucks and not showing the console.logs(). What I am doing wrong over here. Any help is very much appreciated.

I would suggest following the code structure as suggested in socket.io docs.

Also, you should not be calling io.listen or io.on('connection') inside your testStream express middleware. These are things you should only be doing once, and ideally they should happen during startup, inside app.js and not in reaction to a POST request. In fact, I'm not sure what the purpose of your testStream middleware is, its not even returning any response (eg res.end() )

If you want to handle socket connections in a separate module you can, but instead of exporting your app's server the way you are, try passing the io instance as variable to your submodule. In short, try this:

app.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var test = require('./test')(io);

app.set('port', process.env.PORT || 3000);

server.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

test.js

module.exports = function(io) {
    io.on('connection', function(socket) {
        console.log("in socket");
        fs.readFile('E:/temp/testimg.png', function(err, buf) {
            socket.emit('image', {
                image: true,
                buffer: buf
            });
            console.log("test image");
        });
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM