Configuring Express 4.0 routes with socket.io Configuring Express 4.0 routes with socket.io express express

Configuring Express 4.0 routes with socket.io


SocketIO does not work with routes it works with sockets.

That said you might want to use express-io instead as this specially made for this or if you are building a realtime web app then try using sailsjs which already has socketIO integrated to it.

Do this to your main app.js

app = require('express.io')()app.http().io()app.listen(7076)

Then on your routes do something like:

app.get('/', function(req, res) {    // Do normal req and res here    // Forward to realtime route    req.io.route('hello')})// This realtime route will handle the realtime requestapp.io.route('hello', function(req) {    req.io.broadcast('hello visitor');})

See the express-io documentation here.

Or you can do this if you really want to stick with express + socketio

On your app.js

server = http.createServer(app)io = require('socket.io').listen(server)require('.sockets')(io);

Then create a file sockets.js

module.exports = function(io) {    io.sockets.on('connection', function (socket) {        socket.on('captain', function(data) {            console.log(data);            socket.emit('Hello');        });    });};

You can then call that to your routes/controllers.


The route:

const Router = require('express').Routerconst router = new Router();router.get('/my-route', (req, res, next) => {    console.log(req.app.locals.io) //io object    const io = req.app.locals.io    io.emit('my event', { my: 'data' }) //emit to everyone    res.send("OK")});module.exports = router

The main file:

const app = require('express')()const server = require('http').Server(app);const io = require('socket.io')(server)const myroute = require("./route") //route file dirapp.use(myroute);server.listen(3000, () => {    console.log('¡Usando el puerto 3000!');});app.locals.io = io


I think a better way to do it is to attach the Io server to response object In the first middleware .per the way express is designed the Io server will be available to your subsequent routes.

Check this link