Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save laterbreh/5d7bdf03258152c95b8d to your computer and use it in GitHub Desktop.
Save laterbreh/5d7bdf03258152c95b8d to your computer and use it in GitHub Desktop.
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.
*/
@dkrylovdotcom
Copy link

ulllltra thx :)

@quangtuyen1993
Copy link

thank pro

@Robokishan
Copy link

i am getting error from index.js router undefined

@thuanpham98
Copy link

wow what amazing, good person

@ManuelMurillo
Copy link

amazing, thank you so much

@filicaliva
Copy link

nice, thank you

@yogendrajs
Copy link

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

@aakashpothepalli
Copy link

THANKS A TON!

@spamator12
Copy link

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?

@phamduccongit
Copy link

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?

You say exactly, I had the same problem reloading the page and getting 1 more socket connection And I don't know how to handle it ..

@theJinxrat
Copy link

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?

You say exactly, I had the same problem reloading the page and getting 1 more socket connection And I don't know how to handle it ..

Use app.use(routes) instead app.use("/", routes)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment