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

Socket.IO cannot call 'on'

Socket.IO cannot call 'on'

Problem

I am making a simple node.js app and intend to use socket.io but so far I cannot get the server to start.

This is my code:

var http = require('http'),
    io = require('socket.io'),
    fs = require('fs');

http.createServer(function(request, response){
    fs.readFile(__dirname + '/index.html', function(err, data){
        if(err){
            response.writeHead(500, {'Content-Type': 'text/plain'});
            return response.end('Error');
        }
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end(data);
    });
}).listen(1337);

io.sockets.on('connection', function(socket){
    socket.emit('pic', { addr: '/pic.jpg' });
    socket.on('status', function(data){
        console.log(data);
    })
})

and this is the output i receive:

[[email protected] node]# node server.js

/srv/node/server.js:16
io.sockets.on('connection', function(socket){
           ^
TypeError: Cannot call method 'on' of undefined
    at Object. (/srv/node/server.js:16:12)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)
[[email protected] node]#

Socket.IO was installed by NPM and seems to reside in /root/node_modules/socket.io Because of that I have made a sym-link (ln -s) of that directory to /srv/node where my server root is.

Problem courtesy of: dsljanus

Solution

io is just a library. You want to listen to connect to one specific instance:

var http = require('http'),
    io = require('socket.io'),
    fs = require('fs');

var serv = http.createServer(function(request, response){
    fs.readFile(__dirname + '/index.html', function(err, data){
        if(err){
            response.writeHead(500, {'Content-Type': 'text/plain'});
            return response.end('Error');
        }
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end(data);
    });
});
serv.listen(1337);

// Bind socket.io to server
var serv_io = io.listen(serv);
serv_io.sockets.on('connection', function(socket){
    socket.emit('pic', { addr: '/pic.jpg' });
    socket.on('status', function(data){
        console.log(data);
    })
});
Solution courtesy of: phihag

Discussion

View additional discussion.



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

Share the post

Socket.IO cannot call 'on'

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×