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. I am a tech blogger and an IoT Enthusiast. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. 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!

3 thoughts on “A Simple Chat Server with NodeJS

Leave a Reply

%d bloggers like this: