Skip to content

Instantly share code, notes, and snippets.

@aug2uag
Forked from patrickbrandt/socket.io_Express_Angular.md
Last active January 4, 2022 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aug2uag/79647dad7c7ad6d262d2cec1330c976e to your computer and use it in GitHub Desktop.
Save aug2uag/79647dad7c7ad6d262d2cec1330c976e to your computer and use it in GitHub Desktop.
socket.io Express routes

Create socket.io middleware

Include the following code in your app.js module (other standard Express module dependancies and middleware left out for brevity):

var express = require('express');
var http = require('http');
var io = require('socket.io');
var routes = require('./routes/index');

var app = express();

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Setup custom app middleware
 */

/* setup socket.io */
io = io(server);
app.use(function(req, res, next) {
  req.io = io;
  next();
});
io.on('connection', function(socket) {
  //log.info('socket.io connection made');
  console.log('socket.io connection made');
});

app.use('/', routes);

server.listen('3000');

You can now emit socket.io events from any route handler (./routes/index in this example):

var express = require('express');
var router = express.Router();

router.post('/', function(req, res, next) {
  req.io.emit('some_event');
  //do some stuff
  req.io.emit("some_other_event"); //we did some stuff - emit a related event
});

module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment