
Creating A Simple Chat Server Using NODEJS
23 July 2023In 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 NodeJs – https://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());
});
- Firstly type npm install mqtt in your terminal to install the mqtt module.
- Now, You have to install the file standard. So, type npm install fs.


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!
Hey there, I’m Anshul Pal, a tech blogger and Computer Science graduate. I’m passionate about exploring tech-related topics and sharing the knowledge I’ve acquired. With two years of industry expertise in blogging and content writing, I’m also the co-founder of HVM Smart Solution. Thanks for reading my blog – Happy Learning!