Creating A Simple Chat Server Using NODEJS

Creating A Simple Chat Server Using NODEJS

23 July 2023 0 By Anshul Pal

In this tutorial we are going to create a simple chat server using the NodeJS programming language. Firstly, you need to install the latest version of NodeJS on your machine, then you have to install some required npm packages. Here in this tutorial I’m going to use MQTT IOT Protocal. So, I use the hivemq MQTT Broker. Let’s start our journey by following all the instructions step by step.

Install NodeJshttps://nodejs.org/en

Instructions – Create a folder then copy the given code and create two files.

Chat Server Code

chatserver.js


var mqtt = require('mqtt');
const fs = require('fs');
var client = mqtt.connect('mqtt://broker.hivemq.com:1883');
client.on('connect', () => {
console.log('Connected to Chat Server');
client.subscribe('chat');
});
client.on('close', () => {
console.log('Chat Server closed');
});
client.on('message', (topic, message) => {
console.log(message);
});

 

Chat Client.js

var mqtt = require('mqtt');
const fs = require('fs');
const readline = require('readline');
var client = mqtt.connect('mqtt://broker.hivemq.com:1883');
const rl = readline.createInterface({
input:process.stdin,
output:process.stdout
});
var userName = 'Unknown';
client.on('connect', () => {
console.log('Connected to Chat Server');
client.subscribe('chat');
rl.question('Enter your name:', (answer) => {
userName=answer;
rl.on('line', (input) => {
client.publish('chat',userName+" says : "+input);
});
});
});
client.on('close', () => {
console.log('Chat Server closed');
});
client.on('message', (topic, message) => {
console.log(message.toString());
});

After saving both files open your terminal and install the three packages as you can see in the below images.
  1. Firstly type npm install mqtt in your terminal to install the mqtt module.
  2. Now, You have to install the file standard. So, type npm install fs.
Node MQTT
Now you have to install the readline module. So type npm install readline.NPM Node

After installing it all. It’s time to run your code and you will successfully connect.

Now open another terminal and type node ChatClient.js for run code. You can run chatclient.js code on any device that supports nodejs. Now your chat server is ready for use.

We hope that you like our tutorial. If you found any error during the connection or related to our code, then please leave a comment below.

Suggested readings!