Thursday, March 28, 2024
ProgrammingTech/Web

A Simple Chat Server with NodeJS

In this tutorial we create a simple chat server. Code written in Nodejs so you need to install latest version of Nodejs and install some required npm packages.  Here i use MQTT IoT Protocol .  So i used Mosquitto MQTT Broker.

How To install Nodejs

visit this link : https://iotbyhvm.ooo/how-to-install-node-js-on-ubuntu/

Chat Server Code

ChatServer.js

var mqtt = require('mqtt');
const fs = require('fs');
var client = mqtt.connect('mqtt://test.mosquitto.org: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);
});

Now open terminal and type node ChatServer.js for run code.
Chat Client.js
var mqtt = require('mqtt');
const fs = require('fs');
const readline = require('readline');
var client = mqtt.connect('mqtt://test.mosquitto.org: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());
});

Now open another terminal and type node ChatClient.js for run code. You can run chatclient.js code in any device that support nodejs. Now your chat server Ready for use.

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

3 thoughts on “A Simple Chat Server with NodeJS

Leave a Reply

Your email address will not be published. Required fields are marked *