Socket.io error hooking into express.js
For socket.io to work with express, you need a server instance and therefore attach it to socket.io
I'll use .listen method of express since it returns an http.Server object. Read the docs here
const port = 3000,
app = require('express')(),
io = require('socket.io')();
// Your normal express routes go here...
// Launching app
const serverInstance = app.listen(port, () => {
console.log('App running at http://localhost:' + port);
});
// Initializing socket.io
io.attach(serverInstance);
You can do it without using http
module
app.listen return a server instance you can use for socket.io
const express = require('express');
const app = express();
const server = app.listen(port, () => {
console.log("Listening on port: " + port);
});
const io = require('socket.io')(server);
You should use http
module:
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server); //pass a http.Server instance
server.listen(80); //listen on port 80
//now you can use app and io
More details you can find in a documentation: http://socket.io/docs/#using-with-express-3/4