In our last tutorial, we set up our node js server. In this tutorial, we build on it and learn how to send messages to and from our server, for this we are using node js and socket IO. The first thing we want to do is install socket.io, we do this using our computer’s command console. Navigate to your project folder and run the command:
>npm install socket.io
This makes Npm will then install socket.io. Next, we open up our app.js file and add a few lines of code:
var io = require('socket.io')(http);
io.sockets.on('connection', function (socket) {
console.log('new connection');
});
All this code does is spit out a message in the node console whenever there is a new socket.io connection. Save the file and start your server. Next, we edit our index.html and add this to our head:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
<script>
Both sides are now ready for testing, start your server and open up a web browser to localhost:2000. You should see a message claiming there is a new connection as soon as you load your site. This means everything is working and we can move forward to requests.
add this code to your index.html right underneath var socket = io();
setInterval(function () {
socket.emit('hello server', Math.floor((Math.random() * 10) + 1));
}, 1000);
This code sends a ‘hello server’ message with a number between 1 and 10. Next we need to edit our app.js so that it can respond to the request, add this code inside your io.sockets.on function:
socket.on('hello server', function (data) {
console.log('client said hello with a ' + data);
});
This code just logs the random number that your client sent. Now we can do this both ways. Try copying the socket.on function from your app.js to your index.html and the socket
That’s all for this tutorial hope you enjoyed, you can check out the other tutorials in this series here.