wvb1
wvb1

Reputation: 63

Socket.io is not working with my node/express application

I am using openshift with express and no matter what configuration I change socket.io to it breaks my application. What am I missing?

I have commented out the sections that use socket.io and the app runs fine. When I uncomment socket.io everything goes wrong. I have tried changing the position of the code to accept the standard io.listen(app), but it still breaks. I have also tried numerous examples from the internet.

Is this possible? //self.io.listen(self.app); if not what should I have socket.io listen to in the context of my app? I cannot call io.listen(server)..

var express = require('express');
//etc

// configuration     
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); 

var App = function(){

 // Scope
 var self = this;

 // Setup
 self.dbServer = new      mongodb.Server(process.env.OPENSHIFT_MONGODB_DB_HOST,parseInt(process.env.O PENSHIFT_MONGODB_DB_PORT));
 self.db = new mongodb.Db(process.env.OPENSHIFT_APP_NAME,    self.dbServer, {auto_reconnect: true});
 self.dbUser = process.env.OPENSHIFT_MONGODB_DB_USERNAME;
 self.dbPass = process.env.OPENSHIFT_MONGODB_DB_PASSWORD;

 self.ipaddr  = process.env.OPENSHIFT_NODEJS_IP;
 self.port    = parseInt(process.env.OPENSHIFT_NODEJS_PORT) || 8080;
 if (typeof self.ipaddr === "undefined") {
  console.warn('No OPENSHIFT_NODEJS_IP environment variable');
 };

 // Web app urls
 self.app  = express();


 //self.io  = require('socket.io');
 //self.clients = [];

 /*self.io.sockets.on('connection', function (socket) {
      self.clients.push(socket);

      socket.emit('welcome', { message: 'Welcome!' });

      // When socket disconnects, remove it from the list:
      socket.on('disconnect', function() {
          var index = self.clients.indexOf(socket);
          if (index != -1) {
              self.clients.splice(index, 1);
          }
      });

  });*/



  // set up our express application
  self.app.use(morgan('dev')); // log every request to the console
  self.app.use(cookieParser()); // read cookies (needed for auth)
  self.app.use(bodyParser.json()); // get information from html forms
  self.app.use(bodyParser.urlencoded({ extended: true }));
  self.app.use(bodyParser());
  self.app.use(multer({ dest: process.env.OPENSHIFT_DATA_DIR}));
  self.app.use(compression());
  self.app.use(express.static(__dirname + '/public'));
  self.app.use("/public2",    express.static(process.env.OPENSHIFT_DATA_DIR));
  self.app.set('view engine', 'ejs'); // set up ejs for templating
  self.app.use(function (req, res, next) {
      res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
      res.setHeader('Access-Control-Allow-Credentials', 'true');
      next();

  }
 );

  // required for passport
  self.app.use(session({
secret:'example',
   maxAge: 6 * 3 * 60 * 1000,
   store:  new MongoStore({ url: process.env.OPENSHIFT_MONGODB_DB_URL,
   clear_interval: 6 * 3 * 60 * 1000 })
  }));

  self.app.use(passport.initialize());
  self.app.use(passport.session()); // persistent login sessions
  self.app.use(flash()); // use connect-flash for flash messages stored in session

 require('./app/routes.js')(self.app, passport); // load our routes and    pass in our app and fully configured passport

 self.connectDb = function(callback){
  self.db.open(function(err, db){
  if(err){ throw err };
  self.db.authenticate(self.dbUser, self.dbPass, {authdb: "admin"},    function(err, res){
    if(err){ throw err };
    callback();
   });
  });
 };


 //starting the nodejs server with express
 self.startServer = function(){
 self.app.listen(self.port, self.ipaddr, function(){
  console.log('%s: Node server started on %s:%d ...', Date(Date.now()),   self.ipaddr, self.port);
   });

  //websockets
   //self.io.listen(self.app);

 };

 // Destructors
 self.terminator = function(sig) {
  if (typeof sig === "string") {
    console.log('%s: Received %s - terminating Node server ...',    Date(Date.now()), sig);
   process.exit(1);
   };
  console.log('%s: Node server stopped.', Date(Date.now()) );
 };

 process.on('exit', function() { self.terminator(); });

 self.terminatorSetup = function(element, index, array) {
  process.on(element, function() { self.terminator(element); });
 };

 ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGPIPE', 'SIGTERM'].forEach(self.terminatorSetup);

};

 //make a new express app
 var app = new App();

 //call the connectDb function and pass in the start server command
 app.connectDb(app.startServer);

Upvotes: 2

Views: 591

Answers (1)

wvb1
wvb1

Reputation: 63

Thank you for your comments. The solution was to create a self.server variable to pass the express server into socket.io. I have tested the connection and it is working fine now; with all of the other server dependencies.

   //starting the nodejs server with express

  self.startServer = function(){
  self.server = self.app.listen(self.port, self.ipaddr, function(){
  console.log('%s: Node server started on %s:%d ...', Date(Date.now()),     self.ipaddr, self.port);
 });

  //websockets
  self.io  = require('socket.io').listen(self.server);

  };

Upvotes: 2

Related Questions