In the following chapter, we will discuss the basic example using the Socket.IO library along with ExpressJS.
Example
First of all, 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('E:/test/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. If everything goes well a message saying “Hello World” is printed on the page.
Following is another example (this require Socket.IO), it 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('E:/test/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
Next Topic:-Click Here