Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Socket.io and Express on NodeJS

Socket.io and Express on NodeJS

Problem

im trying to build a simple application with [email protected], and [email protected].

Ive generate the skel of my app with express generator:

express --sessions --css stylus --ejs myapp

I edited then the package.json file to include socket.io:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app"
  },
  "dependencies": {
    "express": "3.0.0rc4",
    "ejs": "*",
    "stylus": "*",
    "socket.io": "*"
  }
}

and ran npm install. Socket.io got installed correctly.

I opened the app.js file, required socket.io, set it to listen the server, but when adding event handlers with

io.sockets.on('connection', callback.. bla bla bla);

I get

io.sockets.on('connection', function(socket) {
           ^
TypeError: Cannot call method 'on' of undefined

I get

   info  - socket.io started

when running, so socket.io is initializing, but there doesnt seems to be a io.sockets module.

Ive ran console.log(io); to explore the object and I got:

{ version: '0.9.10',
  protocol: 1,
  clientVersion: '0.9.10',
  listen: [Function],
  Manager: 
   { [Function: Manager]
     defaultTransports: [ 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling' ] },
  Transport: [Function: Transport],
  Socket: [Function: Socket],
  Static: [Function: Static],
  Store: { [Function: Store] Client: [Function] },
  MemoryStore: { [Function: Memory] Client: [Function: Client] },
  RedisStore: { [Function: Redis] Client: [Function: Client] },
  parser: 
   { packets: 
      { disconnect: 0,
        connect: 1,
        heartbeat: 2,
        message: 3,
        json: 4,
        event: 5,
        ack: 6,
        error: 7,
        noop: 8 },
     reasons: 
      { 'transport not supported': 0,
        'client not handshaken': 1,
        unauthorized: 2 },
     advice: { reconnect: 0 },
     encodePacket: [Function],
     encodePayload: [Function],
     decodePacket: [Function],
     decodePayload: [Function] } }

So where is the sockets method? Nowhere. But look, there is a Socket function:

Socket: [Function: Socket]

So I thought maybe documentation is deprecated and sockets became Socket. So I did console.log(io.Socket); and got

  this.id = id;
  this.namespace = nsp;
  this.manager = manager;
  this.disconnected = false;
  this.ackPackets = 0;
  this.acks = {};
  this.setFlags();
  this.readable = readable;
  this.store = this.manager.store.client(this.id);
  this.on('error', defaultError);

But that Socket.on doesnt seems to be the function im looking.

So how do I set the handlers? At the webpage, github and resources out there all of them uses io.sockets.on().

Notice that I also tried running npm install socket.io separatly

I'll post my app.js just in case, but It doesnt seems to be a problem with my code:

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , io = require('socket.io');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/users', user.list);

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

io.listen(server);

console.log(io.Socket);


io.sockets.on('connection', function(socket) {
  socket.emit('init', { msg: 'Welcome'});
  socket.on('roll', function(data) {
    console.log(data);
  })
});
Problem courtesy of: jviotti

Solution

var app = require('express')()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server)

server.listen(3000)    

io.on('connection',function(socket){
  console.log('connection..')
})
Solution courtesy of: supernova

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Socket.io and Express on NodeJS

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×