Exécutez socket.io 2.0 et Express 4.0+ sur le même port

J’ai déjà installé socket.io sur un projet de nœud sans avoir besoin d’un framework de templates express.

Problème

si j’ajoute cette ligne de code: http.listen(3001, function() { console.log('listening on port 3001'); }); puis en visitant localhost: 3000 j’ai mon application dans laquelle les sockets ne fonctionnent pas et sur localhost: 3001 j’ai des sockets en fonctionnement . Comment puis-je fusionner les deux?

Erreur

 socket.io.js:2 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LpQ6zKP net::ERR_CONNECTION_REFUSED 

J’essaie d’append socket.io dans un cadre express comme ci-dessous:

fichier app.js

 const express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var expressValidator = require('express-validator'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser'); var flash = require('connect-flash'); var multer = require('multer'); var upload = multer({ dest: './uploads' }); var mongo = require('mongodb'); var mongoose = require('mongoose'); var db = mongoose.connection; var index = require('./routes/index'); var app = express(); var http = require( "http" ).createServer( app ); var io = require( "socket.io" )( http ); http.listen(3000, "127.0.0.1"); var httpk = require('http'); var nsp = io.of('/channel1'); var connectCounter = 0; var interval = undefined; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect jQuery JS app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect Bootstrap CSS // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); //Handle express sessions app.use(session({ secret:'secret', saveUninitialized: true, resave:true })); // Passport app.use(passport.initialize()); app.use(passport.session()); // Validator app.use(expressValidator({ errorFormatter: function(param, msg, value) { var namespace = param.split('.') , root = namespace.shift() , formParam = root; while(namespace.length) { formParam += '[' + namespace.shift() + ']'; } return { param : formParam, msg : msg, value : value }; } })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); //For flash messages app.use(flash()); app.use(function (req, res, next) { res.locals.messages = require('express-messages')(req, res); next(); }); app.get('*', function(req, res, next){ res.locals.user = req.user || null; next(); }); app.use('/', index); function test() { httpk.get("api-url", function(res) { var body = ''; res.on('data', function(data) { body += data; }); res.on('end', function() { var parsed = JSON.parse(body); //console.log(parsed.data.product1); var dataArray = []; dataArray.push((parseFloat(parsed.data.product1) + Math.random() * 0.1 + 0.01).toFixed(2)); dataArray.push((parseFloat(parsed.data.product2) + Math.random() * 0.1 + 0.01).toFixed(2)); console.log(dataArray); nsp.emit('live-quote', dataArray); }); }); } nsp.on('connection', function(socket) { socket.on('pass_data', function(my) { console.log(my); }); //Make a http call connectCounter++; if (interval === undefined) interval = setInterval(test, 1000); nsp.emit('live-users', connectCounter); console.log('1 user connected, Total Joined: ' + connectCounter); socket.on('disconnect', function() { connectCounter--; if (connectCounter <= 0 && interval !== undefined) interval = clearInterval(interval); nsp.emit('live-users', connectCounter); console.log('1 user disconnected, Total Left: ' + connectCounter); }); console.log("total clients: " + io.engine.clientsCount); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; 

head.ejs

       

jsdefaults.ejs

     $(function() { var socket = io('/channel1'); var currentTime; socket.on('live', function(msg) { console.log("msg: "+msg); }); socket.on('live-users', function(users) { $('#total').text(users); }); });  

index.ejs

      

On dirait que vous avez utilisé express-generator pour configurer votre application Express. Dans ce cas, le serveur HTTP sera configuré dans bin/www et c’est là que le serveur socket.io doit également être configuré (puisque vous voulez partager le socket.io serveur). Serveur HTTP entre Express et socket.io ).

Le bin/www par défaut contient ceci:

 /** * Create HTTP server. */ var server = http.createServer(app); 

C’est là que vous ajoutez le serveur socket.io :

 var server = http.createServer(app); var io = require('socket.io')(server); var nsp = io.of('/channel1'); nsp.on('connection', ...);