Socket.IO cannot call 'on'

I am making a simple node.js application and intend to use socket.io, but so far I can not start the server.

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 result that I get:

 [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 be located in / root / node_modules / socket.io Because of this, I created sym-link (ln -s) of this directory in / srv / node, where is my server root.

+8
linux webserver
source share
1 answer

io is just a library. You want to listen to the connection 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); }) }); 
+25
source share

All Articles