Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.IO cannot call 'on'

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:

[root@ip-10-224-55-226 node]# node server.js

/srv/node/server.js:16
io.sockets.on('connection', function(socket){
           ^
TypeError: Cannot call method 'on' of undefined
    at Object.<anonymous> (/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)
[root@ip-10-224-55-226 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.

like image 349
dsljanus Avatar asked Feb 07 '13 12:02

dsljanus


1 Answers

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);
    })
});
like image 124
phihag Avatar answered Nov 04 '22 00:11

phihag