Forked from laterbreh/Express 4 and Socket.io: Passing socket.io to routes - app.js
Created
January 14, 2021 08:01
-
-
Save mrhung/503fe0c6f79dbc5f24e835ef1c3dadc1 to your computer and use it in GitHub Desktop.
Express 4 and Socket.io: Passing socket.io to routes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var app = express(); | |
| app.io = require('socket.io')(); | |
| var routes = require('./routes/index')(app.io); | |
| app.use('/', routes); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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. | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment