First we have to understand what is WebSocket. WebSocket is a bi-directional communications protocol that provides continuous connection between a client and a server. This protocol is mainly used to build real time applications like chatting/messaging applications or real time dashboards etc.
Let us create a realtime one-to-one chatting application using Node.js and WebSocket. Also we will be using Node.js Express module to create the application.
First we have to create a Node.js application.
Let's open a terminal and create a folder called "my-chat-app". Then run " npm init " command to setup a Node.js project. I hope you already have Node.js installed in your machine. If you do not have Node.js installed then check my below tutorial on Node.js and install Node.js in your system.
How to create a basic RESTful API using Node.js and Express Framework
Next we have to install the dependencies that are required to build this application. Install the below dependencies using NPM package manager.
Now create two files called index.js and index.html inside the my-chat-app folder.
Open the index.js file and paste the below code:
Next open the index.html file and paste the below code:
To run this go to command prompt or terminal and run the command " node index.js " and open the url " http://localhost:5000/ " in browser.
Demo:
Let us create a realtime one-to-one chatting application using Node.js and WebSocket. Also we will be using Node.js Express module to create the application.
First we have to create a Node.js application.
Let's open a terminal and create a folder called "my-chat-app". Then run " npm init " command to setup a Node.js project. I hope you already have Node.js installed in your machine. If you do not have Node.js installed then check my below tutorial on Node.js and install Node.js in your system.
How to create a basic RESTful API using Node.js and Express Framework
mkdir my-chat-app
cd my-chat-app
npm init
Next we have to install the dependencies that are required to build this application. Install the below dependencies using NPM package manager.
- Express
- Websocket
// Install node express package
npm install express --save
// Install node websocket module
npm install websocket --save
Now create two files called index.js and index.html inside the my-chat-app folder.
Open the index.js file and paste the below code:
// Import the path, express and websocket module
var path = require('path');
var express = require('express');
var webSocketServer = require('websocket').server;
// Create an express app
var app = express();
// Set the port number
app.set('port', (process.env.PORT || 5000));
// Read the index.html and send the file
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Start the server
var server = app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
// Create e a connection map
var connections = {};
// Create the websocket server
var wsServer = new webSocketServer({
httpServer: server
});
// Bind various events with the websocket server
wsServer.on('request', function(request) {
console.log((new Date()) + " Connection from origin " + request.origin + ".");
var connection = request.accept(null, request.origin);
var connectionId = null;
connection.on('message', function(message) {
if (message.type === 'utf8') {
var receivedData = JSON.parse(message.utf8Data);
connectionId = receivedData.name;
if (!connections[connectionId]) {
connections[connectionId] = connection;
}
var type = receivedData.type;
if (type == "message") {
send(receivedData.sendTo, {"type": "newMessage", "from": connectionId, "message": receivedData.message});
}
}
});
connection.on('close', function(connection) {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.", "connectionId: " + connectionId);
if (connections[connectionId]) {
delete connections[connectionId];
}
});
});
// Send messages
var send = function(connectionId, payload) {
if (connections[connectionId]) {
var json = JSON.stringify(payload);
connections[connectionId].sendUTF(json);
}
};
Next open the index.html file and paste the below code:
To run this go to command prompt or terminal and run the command " node index.js " and open the url " http://localhost:5000/ " in browser.
node index.js
Demo:
You there, this is really good post here. Thanks for taking the time to post such valuable information. chatting dirty
ReplyDeleteGreat Article
ReplyDeleteNode.js Project Topics for Computer Science
FInal Year Project Centers in Chennai
JavaScript Training in Chennai
JavaScript Training in Chennai