Merge pull request #2 from BRAVO68WEB/dev

Implimenting WS Listeners
This commit is contained in:
Jyotirmoy Bandyopadhayaya 2023-01-14 06:35:28 +00:00 committed by GitHub
commit 766f994ce6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 119 additions and 21 deletions

View File

@ -4,6 +4,14 @@ import { hideBin } from 'yargs/helpers'
const argv = yargs(hideBin(process.argv)).argv
import axios from 'axios'
import chalk from 'chalk'
import ws from 'ws';
const client = new ws('ws://localhost:3000');
client.on('open', () => {
// Causes the server to print "Hello"
client.send('Hello');
});
if (argv.url && argv.username && argv.authkey) {
const {
@ -11,6 +19,7 @@ if (argv.url && argv.username && argv.authkey) {
authkey,
url
} = argv
if (typeof username === 'string' && typeof authkey === 'string' && typeof url === 'string') {
const config = {
url: url + "/status/heartbeat/" + username + "?auth=" + authkey,
@ -20,7 +29,7 @@ if (argv.url && argv.username && argv.authkey) {
function sendHeartbeat() {
axios(config)
.then(function (response) {
if(response.data.updateUserStatus.username == username){
if(response.data?.updateUserStatus?.username == username){
console.log(chalk.green("User Status Ping Successfully"))
}
else{
@ -38,7 +47,6 @@ if (argv.url && argv.username && argv.authkey) {
sendHeartbeat()
}, 60000)
} else {
console.log(chalk.red('Username')+', '+url+' and '+authkey+'must be strings')
}
} else {

View File

@ -10,6 +10,7 @@
"dependencies": {
"axios": "^0.27.2",
"chalk": "^5.0.1",
"ws": "^8.8.1",
"yargs": "^17.4.1"
},
"type": "module",

View File

@ -141,6 +141,11 @@ wrap-ansi@^7.0.0:
string-width "^4.1.0"
strip-ansi "^6.0.0"
ws@^8.8.1:
version "8.8.1"
resolved "https://registry.yarnpkg.com/ws/-/ws-8.8.1.tgz#5dbad0feb7ade8ecc99b830c1d77c913d4955ff0"
integrity sha512-bGy2JzvzkPowEJV++hF07hAD6niYSr0JzBNo/J29WsB57A2r7Wlc1UFcTR9IzrPvuNVO4B8LGqF8qcpsVOhJCA==
y18n@^5.0.5:
version "5.0.8"
resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55"

View File

@ -1,10 +1,13 @@
const express = require("express");
const { createServer } = require('http');
const session = require("express-session");
const mdb = require("./config/mongodb");
const mongoStore = require("connect-mongo");
const keys = require("./config/keys");
const app = express();
const axios = require("axios");
// const axios = require("axios");
const { WebSocketServer } = require("ws");
const { parse } = require("url");
app.use(
session({
@ -20,24 +23,62 @@ app.use(
})
);
// Self pinger as status updater
setInterval(() => {
const config = {
url: `http://localhost:${process.env.PORT}/status/ping/${keys.pingusername}`,
}
axios(config)
.then(function (response) {
console.log("Self Ping Completed");
})
.catch(function (error) {
console.log(error);
}
);
}, 120000);
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });
const wss3 = new WebSocketServer({ noServer: true });
wss1.on('connection', function connection(ws, request, socket) {
ws.on('message', function message(data) {
console.log(`Received message ${data} from user`);
});
ws.send('echo !!');
socket.destroy();
});
wss2.on('connection', function connection(ws) {
console.log("Client connected to wss2");
ws.send('Connected to Server!!');
ws.on('message', function message(data) {
console.log(`Received message ${data} from user ${client}`);
});
});
// wss2.on('close', function close(ws) {
// console.log('disconnected');
// ws.send('Goodbye!');
// })
wss3.on('connection', function connection(ws, socket) {
ws.send('No response');
socket.destroy();
});
app.use("/", require("./routes"));
app.use("/", require("./routes"));
const PORT = process.env.PORT || 5000;
const server = createServer(app);
app.listen(PORT, () => {
server.on('upgrade', function upgrade(request, socket, head) {
const { pathname } = parse(request.url);
if (pathname === '/') {
wss1.handleUpgrade(request, socket, head, function done(ws) {
wss1.emit('connection', ws, request, socket);
});
} else if (pathname === '/status') {
wss2.handleUpgrade(request, socket, head, function done(ws) {
// wss2.emit('connection', ws, request);
wss2.emit('connection', ws, request);
// wss2.emit('close', ws, request);
});
} else {
wss3.handleUpgrade(request, socket, head, function done(ws) {
wss3.emit('connection', ws, socket);
});
}
});
server.listen(PORT, () => {
console.log("API listening on port "+ PORT + "!");
});

View File

@ -22,7 +22,7 @@ module.exports.checkStatus = async (req, res, next) => {
const userStatus = await UserStatus.findOne({
username: req.params.username
});
var lastPingTs = (format(userStatus.lastSeen, "x"));
var lastPingTs = (format(userStatus?.lastSeen, "x"));
var currentTs = (format(new Date(), "x"));
// var diff = currentTs - lastPingTs;
// console.log(diff/60000);

View File

@ -0,0 +1,37 @@
const wss1c = (wsc) => {
wsc.on('connection', function connection(ws, request, socket) {
ws.on('message', function message(data) {
console.log(`Received message ${data} from user`);
});
ws.send('echo !!');
socket.destroy();
});
}
const wss2c = (wsc) => {
wsc.on('connection', function connection(ws) {
ws.send('Client connected !!');
ws.on('message', function message(data) {
console.log(`Received message ${data} from user`);
ws.send('echo !!');
});
});
wsc.on('close', function close(ws) {
console.log('disconnected');
ws.send('Goodbye!');
})
}
const wss3c = (wsc) => {
wsc.on('connection', function connection(ws, socket) {
ws.send('No response');
socket.destroy();
});
}
module.exports = {
wss1c,
wss2c,
wss3c
}

View File

@ -23,7 +23,8 @@
"express-session": "^1.17.2",
"helmet": "^5.0.2",
"mongoose": "^6.3.0",
"nanoid": "^3.3.2"
"nanoid": "^3.3.2",
"ws": "^8.8.1"
},
"devDependencies": {
"nodemon": "^2.0.16"

View File

@ -1449,6 +1449,11 @@ write-file-atomic@^3.0.0:
signal-exit "^3.0.2"
typedarray-to-buffer "^3.1.5"
ws@^8.8.1:
version "8.8.1"
resolved "https://registry.yarnpkg.com/ws/-/ws-8.8.1.tgz#5dbad0feb7ade8ecc99b830c1d77c913d4955ff0"
integrity sha512-bGy2JzvzkPowEJV++hF07hAD6niYSr0JzBNo/J29WsB57A2r7Wlc1UFcTR9IzrPvuNVO4B8LGqF8qcpsVOhJCA==
xdg-basedir@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/xdg-basedir/-/xdg-basedir-4.0.0.tgz#4bc8d9984403696225ef83a1573cbbcb4e79db13"