Before reading post, please go through my previous posts: “Express JS WebApplication with Enide Studio 2014 IDE” and “Express JS Routings with Enide Studio 2014 IDE”.
Introduction to Socket IO
Node JS: Socket IO Module is used to develop Real-time Client-Server Communication applications. It internally uses “WebSocket” Programming model to provide real-time two-way communication between Client and Server.
We can observe that the following Technologies offer WebSocket Programming to implement this kind of applications.
- HTML5 WebSocket
- Java EE 7 WebSocket API
- Node JS:Socket IO Module
Difference between Traditional HTTP and WebSocket Approaches
Traditional HTTP Approach:
We have our old and Traditional HTTP Request-Response Stateless Approach to provide Communication between Client and Server. But it follows “Pushing” model that means when client sends a request to Server, Server pushes the response to the Clients.
WebSocket Approach:
We can use WebSocket Approach too to provide Communication between Client and Server. However unlike Traditional HTTP Request-Response Stateless Approach, WebSocket Approach provides Communication between Client and Server by using “Pulling” model that means Server always pulls data to Clients. That’s why is is more efficient and faster approach to provide Client-Server Communication.
Advantages of Socket IO(WebSocket) Programming:
- Faster and Two-way Communication
- Cross-Browser Support
- Cross-Platform Support
- Platform independent web framework
Socket IO Setup
Unlike some Node JS Default Modules like “npm”,”http”,”events” come with Node JS Platform basic installation (No need of separate steps to install these modules), Socket.IO does not come with as Node JS Default modules. We need to install it manually.
We have already discussed on “How to install a Node JS Module” using “node install” command. If you are not familiar about this command, please go through my previous post : “NPM install update and uninstall example”
To install Socket.IO globally
Before staring Express JS Development, first and fore most step We need to do is use “npm install” command to install Express JS module
1 2 3 |
npm install -g socket.io |
Here “socket.io” means Socket IO Module and “-g” means install Socket.io Module globally.
To verify installation
After Socket IO Module installation is done, we need to check whether this module is installed successfully or not. If it is installed successfully, we can find a new folder at
C:Users[Windows_USerName]AppDataRoamingnpmnode_modulessocket.io as shown below:
Socket IO Example
-
- Create a Node.js:Express JS Project with default settings: “socketio” (Please refer my previous post “Express JS WebApplication with Enide Studio 2014 IDE” for more details.)
- Update “package.json” file with “socket.io” module dependency.
Default package.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
{ "name": "socketio", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.12.4", "cookie-parser": "~1.3.5", "debug": "~2.2.0", "express": "~4.12.4", "jade": "~1.9.2", "morgan": "~1.5.3", "serve-favicon": "~2.2.1" } } |
Updated package.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "name": "socketio", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.12.4", "cookie-parser": "~1.3.5", "debug": "~2.2.0", "express": "~4.12.4", "jade": "~1.9.2", "morgan": "~1.5.3", "serve-favicon": "~2.2.1", "socket.io": "~1.3.5" } } |
- Observe default “node_modules” folder
If we observe our project now, it contains all default Express JS Module libraries as shown below:
- Update “node_modules” with “socket.io” library.
In order to use Socket IO module library, we need to execute the following command at our project root directory:
1 2 3 |
npm install --save socket.io |
Here “–save” option means retrieve “socket.io” library from our Local repository and add this to our project. This is something similar to adding JAR files to our Java Project.
Open command prompt at our project root directory and execute above command:
NOTE:- Please ignore those errors or warnings.
Now refresh your “socketio” project in Enide IDE Studio 2014 IDE and observe newly added socketio library to our project as shown below:
- Update app.js with the following content:
app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// Required Modules var express = require('express'); var path = require('path'); var http = require('http'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var io = require('socket.io'); // Routings var index = require('./routes/index'); var user = require('./routes/users'); // Create Express App var app = express(); app.set('port', process.env.PORT || 3000); //view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', user); var server = http.createServer(app); io.listen(server); io.sockets.on('connection', function (socket) { socket.on('messageChange', function (data) { console.log(data); socket.emit('receive', data.message.split('').reverse().join('') ); }); }); server.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); module.exports = app; |
Code Explanation
- Line No 1-9, importing all required dependency Node JS modules into our application
- Line No 12-13, importing Routings into our application
- Line No 16, Create Express JS Application object
- Line No 17, Set Express WebServer port to listen. This is how we can set our desired port number.
- Line No 20-21, Define our application View Template Engine i.e. JADE
- Line No 33, Create an HTTP Server
- Line No 34, Wrap HTTP Server with Socket IO(WebSocket)
- Line No 36-41, io.sockets.on() to open a WebSocket connection between Client and Server.
- Line No 47, Export our application.
- Update index.jade file with the following content:
/views/index.jade
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
extends layout block content h1= title p Welcome to span.received-message #{example} input(type="text", class="message", onkeyup='send(this)') script(src="https://www.journaldev.com/socket.io/index.js") script. var socket = io.connect('https://localhost'); socket.on('receive', function (message) { console.log('received %s', message); document.querySelector('.received-message').innerText = message; }); function send(input) { console.log(input.value) var value = input.value; console.log('Sending Client Message: %s to Server', value); socket.emit('messageChange', {message: value}); } |
- Update index.js file with the following content:
/routes/index.js
1 2 3 4 5 6 7 8 9 10 |
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { example: 'Node Express JS: Socket.IO Module', title: 'Socket.IO Module' }); }); module.exports = router; |
- Final project structure looks like this:
Execute Socket IO Example
- Open command prompt at our project root directory and execute below command:
1 2 3 |
npm start |
- Run Socket IO Example and observe the output
Access application using this URL: https://localhost:3000/
To see WebSocket power Internally, please use Mouse Right Click and Select “Inspect Element” as shown below:
Select “Console” tab. Type some text in “Textbox” and observe the Console output as shown below:
Our application sends each and every character immediately to server. That’s the beauty of WebSocket Programming.
That’s it about Express: Socket IO Module Example.
In my next post, I will give you another Socket IO Module example without using Express JS WebFramework.