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

i am an IoT Enthusiast and Part Time Tech Blogger.

2 thoughts on “A Simple Chat Server with NodeJS

  • 28th December 2018 at 1:18 am
    Permalink

    Keep going sir we need your next blogger

    Reply

Leave a Reply

%d bloggers like this: