WebSocket is an Internet protocol facilitating real-time data transfer between server and client. Once the connection between server and client is established, this connection stays open allowing the free flow of data between the two parties. As a result, WebSocket protocol is very useful to create application requiring continuous real-time data transfer such as chat application for example.

 

In Node.js, as usual, to start building an application, we need to create a package.json first by writing on Terminal window:

 

npm init

 

In consequence, a package.json file is created and there are useful information inside:

 

// package.json

{
  "name": "chat-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

 

In Node.js, to build chat application using WebSocket protocol, we can use Socket.io package with Express.js web framework. 

 

npm install express socket.io

 

Next, we could create an index.js file as the entry point for our chat application.

 

// index.js
// npm install express
// npm install socket.io
// npm install nodemon

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);


const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('<h4>Welcome to Khmer Web Chat App!</h4>');
});

server.listen(port, () => {
  console.log(`listening on *${port}`);
});

 

To run our chat application, we can use nodemon package because it will help us to restart the program each time we change something in the code. Otherwise, we will manually relaunch the application each time we change the code.

 

npm install nodemon

 

One more thing to do is to add a line of code in package.json to be able to use nodemon module correctly.

 

{
  "name": "chat-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1",
    "nodemon": "^2.0.19",
    "socket.io": "^4.5.1"
  }
}

 

Finally, to launch our chat application, we just write the instruction on Terminal window as below:

 

npm start

 

GitHub: https://github.com/Sokhavuth/chat

Heroku: https://khmerweb-chat.herokuapp.com