Full width home advertisement

The world of Angular

Basics of Angular 6 - ng6

Post Page Advertisement [Top]

AppApplicationChatExpressNode.jsWebsocket

How to make a basic realtime one-to-one chat app using Node.js and WebSocket

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

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.
  1. Express
  2. 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: <!--DOCTYPE html--> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>My-chat-app</title> <script> var send = ""; var connect = function() { var nameElement = document.getElementById("name"); name = nameElement.value; if (name == "") { alert("Please enter your name!"); return; } nameElement.disabled = true; document.getElementById("connectButton").disabled = true; var protocol = window.location.protocol.replace(/:/g, ''); var domain = window.location.hostname; var port = window.location.port; if (protocol == "https") { protocol = "wss://"; } else { protocol = "ws://"; } var wsUrl = protocol + domain + ":" + port; var ws = new WebSocket(wsUrl); ws.onopen = function() { send({ "type": "connect", "name": name }); document.getElementById("messageSection").style.display = "block"; }; ws.onerror = function(error) { console.log(error); }; ws.onmessage = function(message) { try { var json = JSON.parse(message.data); if (json.type == "newMessage") { displayMessage(json); } } catch (error) { console.log(error); } }; send = function(data) { if (typeof(ws) != "undefined") { if (ws.readyState == 0) return; if (typeof(data) == "undefined") { data = {}; data["type"] = "message"; data["name"] = name; data["sendTo"] = document.getElementById("sendTo").value; data["message"] = document.getElementById("message").value; document.getElementById("message").value = ""; displayMessage(data, "my"); } ws.send(JSON.stringify(data)); } }; var displayMessage = function(json, side) { var messagesDiv = document.getElementById("messages"); var newMesssageElemet = document.createElement("p"); if(side == "my") { newMesssageElemet.innerHTML = "<b style='color:blue;'>" + name + "</b>" + "("+new Date().toISOString()+"): " + json.message; } else { newMesssageElemet.innerHTML = "<b style='color:red;'>" + json.from + "</b>" + "("+new Date().toISOString()+"): " + json.message; } messagesDiv.insertBefore(newMesssageElemet, messagesDiv.firstChild); } }; </script> </head> <body> <h3>Welcome to My-chat-app</h3> <hr /> Name: <input type="text" id="name" value="" /> <input type="button" id="connectButton" value="Connect" onclick="connect();" /> <br /><br /> <div id="messageSection" style="display:none;"> Send To: <input type="text" id="sendTo" value="" /> <br /> <br /> Message: <input type="text" id="message" value="" /> <br /> <br /> <input type="button" value="Send" onclick="send();" /> <div id="messages"></div> </div> </body> </html>

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:

2 comments:

Bottom Ad [Post Page]