Configuring Express 4.0 routes with socket.io
The route:
const Router = require('express').Router
const 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 dir
app.use(myroute);
server.listen(3000, () => {
console.log('¡Usando el puerto 3000!');
});
app.locals.io = 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 request
app.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.