0

I am trying to integrator socket.io in my express js application (Created by express generator).

Here is the answer i've followed

But it didn't worked.

Added following in bin/www

app.io = require('socket.io')(); app.io.attach(server); 

When i modify app.use('/', index); with app.use('/', require('./routes/index')(app.io)); in app.js file i got the following error

*

Router.use requires middleware function but got undefined

*

1 Answer 1

3

Here is how you can implement socket.io with express.

var express = require('express') var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //serve static files and index.html app.use(express.static(__dirname + '/')); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ //logic handled in here }); http.listen(7000,function(){ console.log('listening on port: 7000'); }); 

The above code has one route for handling the serving of index.html, but of course you can extend with additional routes the same way you would in any other app.

Here is how you can have access to socket.io within a route in express generator.

In www:

var server = http.createServer(app); var io = require('socket.io')(server); module.exports = {io:io} 

Within index.js

router.get('/', function(req, res, next) { var io = require('../bin/www') console.log('I now have access to io', io) res.render('index', { title: 'Express' }); }); 

Note, the above example is purely showing you how to gain access to the io object within index.js. There are many better ways to require socket.io and pass the io object around, but those decisions seem to be outside the scope of this question.

Sign up to request clarification or add additional context in comments.

14 Comments

Where can i add this ??
I want to use io object in routes/index.js but as per yr code everything is do in app.js file
You can make these changes within project_root/bin/www.
But how do i use io in index.js ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.