0

First of all I know a similar question has been asked here, however, I did not understand the answer and my question is worded slightly differently so I am wondering if I can get a more clear answer.

The Express Generator starts an app like so:

app.js

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

I want to use Socket.io so I also install it and require it and following the Socket Docs do this

var server = express.createServer();
var io = require('socket.io')(server);

However, all of my routes, where I really want to handle socket.io events, take place on my routes/index.js page. How do I use socket.io with my router, which is on a different page? How do I pass it in when my server instance was started on app.js (a different page)?

Furthermore, the socket.io docs list two ways to get started with express. The first example shows:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

And the second one shows:

var app = require('express').createServer();
var io = require('socket.io')(app);

app.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Can anyone explain the difference between using the "Express Framework" and "With Express 3 /4" as the documentation differentiates. I would also love to know why the examples use express.createServer() (when a generated express app does not) and why the other example uses both the express and http node modules. Thank you

Community
  • 1
  • 1
Startec
  • 12,496
  • 23
  • 93
  • 160

1 Answers1

0

A working piece of code would be as given below. The important thing here is do all the work with io initialization and io handling once you start listenting on express server. Hope this helps. :-)

var app = require('express')();
var socket_io = require('socket.io');
app.io = socket_io();


//  setup app routes and express settings starts ... 
// .... 
// ...  setup app routes and express settings ends


var server = app.listen(app.get('port') || 3000);
app.io.attach(server);
saurshaz
  • 489
  • 5
  • 17