Create a file called app.js and enter the following code to set up an express application −
var app = require('express')(); var http = require('http').Server(app); app.get('/', function(req, res) { res.sendfile('index.html'); }); http.listen(3000, function() { console.log('listening on *:3000'); });
We will need an index.html file to serve, create a new file called index.html and enter the following code in it −
<!DOCTYPE html> <html> <head> <title>Hello world</title> </head> <body>Hello world</body> </html>
To test if this works, go to the terminal and run this app using the following command −
nodemon app.js
This will run the server on localhost:3000. Go to the browser and enter localhost:3000 to check this.
This sets up our express application and is now serving a HTML file on the root route. Now we will require Socket.IO and will log "A user connected", every time a user goes to this page and "A user disconnected", every time someone navigates away/closes this page.
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res) { res.sendfile('index.html'); }); //Whenever someone connects this gets executed io.on('connection', function(socket) { console.log('A user connected'); //Whenever someone disconnects this piece of code executed socket.on('disconnect', function () { console.log('A user disconnected'); }); }); http.listen(3000, function() { console.log('listening on *:3000'); });
The require('socket.io')(http) creates a new socket.io instance attached to the http server. The io.on event handler handles connection, disconnection, etc., events in it, using the socket object.
We have set up our server to log messages on connections and disconnections. We now have to include the client script and initialize the socket object there, so that clients can establish connections when required. The script is served by our io server at '/socket.io/socket.io.js'.
After completing the above procedure, the index.html file will look as follows −
<!DOCTYPE html> <html> <head> <title>Hello world</title> </head> <script src = "/socket.io/socket.io.js"></script> <script> var socket = io(); </script> <body>Hello world</body> </html>
If you go to localhost:3000 now (make sure your server is running), you will get Hello World printed in your browser. Now check your server console logs, it will show the following message −
A user connected
If you refresh your browser, it will disconnect the socket connection and recreate. You can see the following on your console logs −
A user connected A user disconnected A user connected
We now have socket connections working. This is how easy it is to set up connections in Socket.IO.