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); });
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()); });
Keep going sir we need your next blogger
I didn’t understand what to do with it?& how?
Pingback: MEAN STACKS ? | Introducing the MEAN and MERN Stacks