Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Express 4 and Socket.io: Passing socket.io to routes.
var app = express();
app.io = require('socket.io')();
var routes = require('./routes/index')(app.io);
app.use('/', routes);
//Normal code here
//then at the bottom:
module.exports = function (io) {
//Socket.IO
io.on('connection', function (socket) {
console.log('User has connected to Index');
//ON Events
socket.on('admin', function () {
console.log('Successful Socket Test');
});
//End ON Events
});
return router;
};
/**
* Create HTTP server
*/
var server = http.createServer(app);
app.io.attach(server);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
@laterbreh

This comment has been minimized.

Copy link
Owner Author

@laterbreh laterbreh commented Dec 25, 2015

@rasool1994

This comment has been minimized.

Copy link

@rasool1994 rasool1994 commented Mar 3, 2018

thanks

@felgarte

This comment has been minimized.

Copy link

@felgarte felgarte commented Jun 13, 2018

thanks a lot

@obiwankenoobi

This comment has been minimized.

Copy link

@obiwankenoobi obiwankenoobi commented Sep 6, 2018

dont want to be dramatic but you are a life saver!

@dkrylovdotcom

This comment has been minimized.

Copy link

@dkrylovdotcom dkrylovdotcom commented Sep 27, 2019

ulllltra thx :)

@tuyenps08571

This comment has been minimized.

Copy link

@tuyenps08571 tuyenps08571 commented Nov 16, 2019

thank pro

@Robokishan

This comment has been minimized.

Copy link

@Robokishan Robokishan commented Mar 22, 2020

i am getting error from index.js router undefined

@thuanpham98

This comment has been minimized.

Copy link

@thuanpham98 thuanpham98 commented Apr 6, 2020

wow what amazing, good person

@ManuelMurillo

This comment has been minimized.

Copy link

@ManuelMurillo ManuelMurillo commented Apr 28, 2020

amazing, thank you so much

@filicaliva

This comment has been minimized.

Copy link

@filicaliva filicaliva commented Apr 30, 2020

nice, thank you

@yogendra3236

This comment has been minimized.

Copy link

@yogendra3236 yogendra3236 commented May 14, 2020

Do I also need to call the app route to access socket.io defined inside it?

@aakashpothepalli

This comment has been minimized.

Copy link

@aakashpothepalli aakashpothepalli commented Jun 23, 2020

THANKS A TON!

@spamator12

This comment has been minimized.

Copy link

@spamator12 spamator12 commented Jul 19, 2020

This works only with route associated with index.js, right? So if you have "global" connection/disconnect/reconect events it will duplicate the event and send the emits multiple times?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.