How to install Socket.IO in Node.js

In this tutorial I'm going to explain you how to install Socket.IO in Node.js. In my next tutorials I will explain how to use Socket.IO with Node.js.

Now I will follow the Socket.IO's documentation from here: http://socket.io/docs/

  • Install Node.js.
  • Create a new folder and create a file app.js.
  • Run Command Line and enter npm install socket.io
  • Open your app.js file and add this code:


var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');


app.listen(3000);

function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}

res.writeHead(200);
res.end(data);
});
}

io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});

  • Create a file index.html in the same folder.
  • Add this code in your index.html file:

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:3000');
socket.on('news', function (data) {
alert(data.hello);
socket.emit('my other event', { my: 'data' });
});
</script>

  • Open the command line and enter: node app.js
  • Then, in your browser go to http://localhost:3000/

Video tutorial:









Leave a Comment