I am trying to impliment websocket server for my frontend chart for trading values but whenever i try to change graph pairs its fluctuating my frontend and not clearing privious request here's my server file
const express = require('express');
const path = require('path');
const mysql = require('mysql')
const bodyParser = require('body-parser');
const passport = require('passport');
const exchangeCtrl = require("./controllers/exchange.controller.js");
const webSocketServer = require("websocket").server;
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/static', express.static('public'))
const port = 8000;
var server = app.listen(port, () => console.log(`Server up and running on port
${port} !`));
const wsServer = new webSocketServer({
noServer: true,
path: "/websockets",
httpServer: server,
});
const client = {};
const getUniqueId = () => {
const s4 = () =>
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return s4() + "-" + s4() + "-" + s4();
};
var socketDataVar = "";
wsServer.on("request", function (request) {
var userUd = getUniqueId();
const connection = request.accept(null, request.origin);
client[userUd] = connection;
client[userUd].send(JSON.stringify(userUd));
connection.on("message", async function (message) {
var interval = 1000;
if (message.type === "utf8") {
if (message.utf8Data) {
if (JSON.parse(message.utf8Data) == "disconnect") {
clearInterval(socketDataVar);
} else {
socketDataVar = setInterval(
() => socketData(message.utf8Data),
interval
);
}
}
}
});
const socketData = async (socket) => {
var value = JSON.parse(socket);
var firstCoinId = value.firstCoinId;
var secondCoinId = value.secondCoinId;
var userId = value.userId;
var clientId = value.clientId;
var graphDataApi = await exchangeCtrl.graphData(firstCoinId, secondCoinId);
var topBarApi = await exchangeCtrl.topBar(firstCoinId, secondCoinId);
var filalData = {
graphDataApi,
topBarApi
};
for (key in client) {
client[key].sendUTF(JSON.stringify(filalData));
}
};
});
I am trying to clear the interval and then set the new values but i might think that its not working and i get 2 set of data on each click of frontend
Related
I'm working on a project that involves an application built with Electron that interfaces with an express server, running on Localhost or the home network.
Problem right now is, I'm having trouble getting the server to acknowledge any requests from the application.
Here is my front end logic in the electron application:
let ipAddress;
let port;
let requestAddress;
function connect(){
const ipField = document.getElementById("nu-ip").value;
const portField = document.getElementById("nu-port").value;
port = portField;
if (ipField === "") {
ipAddress = 'localhost';
} else {
ipAddress = ipField;
}
port = portField;
if(port === ""){
requestAddress = `http://$(ipAddress)`;
} else {
requestAddress = `http://${ipAddress}:${port}`;
};
alert(requestAddress);
const request = newXMLHttpRequest();
alert(requestAddress);
request.open("GET",`${requestAddress}/connect`).send();
request.onReadyStateChange = (res) => {
alert(res);
}
}
function startup() {
console.log('Hey where does this show up?')
const NuToggle = document.getElementById("NuHelper-enable");
const NuTools = document.getElementById("Nu-tools");
const connectButton = document.getElementById("connect-button");
NuToggle.addEventListener("change", (event) => {
if(event.target.value === 'enable'){
//alert("NuHelper has been enabled");
NuTools.style.display='block';
connectButton.addEventListener('click', connect);
}
})
}
window.onload = startup;
And here is my server:
//require in our basic dependencies
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const errorHandler = require('errorhandler');
const cors = require('cors');
const PORT = 80;
const app = express();
app.use(morgan('dev'));
app.use(bodyParser);
app.use(errorHandler);
app.use(cors());
app.get('/connect',(req, res, next) => {
res.sendStatus(200);
})
app.listen(PORT, () => {
console.log(`Nu is listening on PORT ${PORT}`);
})
I put 80 into the PORT input and it'll alert "http://localhost:80", but it'll get no response at all from the server, and my logging middleware won't acknowledge that it received any request at all, which makes me think that I'm sending the request to the wrong address. Thanks in advance to anyone who understands how to solve this!
I am developing an REST-API that is running via a load-balancer with a database in MongoDB.
The API works when not using the load-balancer, but when implemented i do not get a response in Postman/Insomia when posting a GET request to the database - on the index ("/") route there in no problem getting a response back though.
But as the title shows, it get this error when canceling the request in PostMan, if like the connection could not be established.
This is the full error:
Error: socket hang up
at connResetException (internal/errors.js:628:14)
at TLSSocket.socketCloseListener (_http_client.js:449:25)
at TLSSocket.emit (events.js:412:35)
at net.js:675:12
at TCP.done (_tls_wrap.js:563:7) {
code: 'ECONNRESET'
}
This is my load-balancer
const https = require ("https");
const httpProxy = require("http-proxy");
const seaport = require("seaport");
const express = require("express");
const fs = require("fs");
const HOST = 'localhost';
const path = require("path")
const PORT = 8080;
const connect = seaport.connect('localhost', 9090);
let i = - 1;
const certificate = {
key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
secure: false
};
let proxy = httpProxy.createProxyServer({secure: false});
let server = https.createServer(certificate, function(req, res) {
let addresses = connect.query('server');
if (!addresses.length) {
res.end('Server failed');
};
i = (i + 1) % addresses.length;
let host = addresses[i].host.split(":").reverse()[0];
let port = addresses[i].port;
proxy.web(req, res, { target: 'https://' + host + ':' + port });
});
server.listen(PORT, function() {
console.log('loadbalancer listens on'+ ":" + PORT)
});
And this is my app.js
const express = require("express");
const app = express();
const morgan = require("morgan")
const bodyParser = require("body-parser")
const https = require('https');
const fs = require('fs');
const seaport = require('seaport');
const path = require('path');
const mongoose = require("mongoose");
//Database
const db = require('./database/db');
const { MongooseDocument } = require('mongoose');
//Routes
const clientRoute = require ("./api/routes/client")
const reservationsRoute = require ("./api/routes/reservations")
app.use('/client', clientRoute);
app.use('/reservations', reservationsRoute);
//index route
app.use('/', (req, res) =>{
res.send('Welcome to the app');
});
//Error handling 1
app.use((req, res, next) => {
const error = new Error("Not found" + " ");
error.status = 400;
next(error);
})
//Error handling 2
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message:("Error 2" + " - " + error.message )
}
});
});
//Create server with the https key and certificate
const sslServer = https.createServer({
key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
}, app);
//Middleware
app.use(morgan("dev"));
app.use(bodyParser.json());
const seaportObject = seaport.connect('localhost', 9090);
//Start listening
let port = seaportObject.register('server');
sslServer.listen(port, () => {
db.mongoConnection()
.then(
console.log('Localserver listens on: ' + port)
)
.catch(err =>{
console.log(err)
res.status(500).json({
error:err,
message: "
It went wrong here "
})
});
});
My Database folder
const mongoose = require('mongoose');
let connection;
const mongoConnection = async () => {
if (!connection) {
connection =
await mongoose.connect("removed",
() => console.log("Mongo is up and running")),{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
}
return connection;
}
module.exports = {
mongoConnection: mongoConnection
};
I am stuck on this subject, please share some guidance
A solution has been found - the problem was that the database never connected
edit: added a bit more code.
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({extended: false})
const {google} = require('googleapis');
const {PubSub} = require('#google-cloud/pubsub');
const iot = require('#google-cloud/iot');
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
app.get('/', urlencodedParser, (req, res) => {
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).send(JSON.stringify({
data: OK
}))).catch(err => res.status(404).send('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
I have this function, that I call after the client initiate: sendCom();
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, deviceId)
const binaryData = Buffer.from(command);
const request = { name: formattedName, binaryData: binaryData, };
client.sendCommandToDevice(request)
.then(responses => {
res.status(200).send(JSON.stringify({ data: OK })).end();
})
.catch(err => {
res.status(404).send('Could not send command. Is the device connected?').end();
});
}
My problem is that sendCommandToDevice gets executed perfectly, however I get the catch error.
As I understand it, it's because in the .then ends the connection.
I've looked at this and thats's what I tried, however I'm not sure I understand what's going on.
You can not use send with end.
end() is used when you want to end the request and want to respond with no data.
send() is used to end the request and respond with some data.
You can found more about it here.
I have this in Google's App Engine (node.js).
My device gets all the commands but I still get the Could not send command. Is the device connected? error.
BTW, already tried this: Await for function before end()
And same result.
Trying to follow this example BTW:
https://cloud.google.com/nodejs/docs/reference/iot/0.2.x/v1.DeviceManagerClient#sendCommandToDevice
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
const iot = require('#google-cloud/iot');
app.get('/', urlencodedParser, (req, res) => {
res.setHeader('Content-Type', 'application/json');
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).end(JSON.stringify({
data: OK
}))).catch(err => res.status(404).end('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
On my end I should get status 200 and OK but it doesn't happen.
I need a Node.js web service that accept a specific POST request that will trigger a publishing in a specific MQTT topic.
I use Express to listen for the request and this part of the script works fine.
The problem is when I it should trigger the publish in topic to perform a downlink.
The code without the Express part works fine. So It seems like Express interfere with MQTT. But the connection to the Broker works fine. Only the publish procedure doesn't work.
var express = require('express');
var bodyParser = require('body-parser');
var mqtt = require('mqtt')
var fs = require('fs')
var path = require('path')
const util = require('util')
var app = express();
var CERT = //certificate
var PORT = //port
var HOST = // host
var options = {
port: PORT,
host: HOST,
clientId: //client_id
username: //uname
password: //pswd
cert: CERT,
rejectUnauthorized: false,
protocol: 'mqtts'
}
var client;
var jsonParser = bodyParser.json();
var port = process.env.PORT || 8080;
app.use(express.static('public'));
app.get('/', function (req, res) {
res.render(__dirname + "/public/index.html");
})
client = mqtt.connect(options);
client.on("connect", () => {
console.log("MQTT connected");
})
client.on('message', function (topic, message) {
var msg = JSON.parse(message)
console.log("topic: " + topic + " msg:" + util.inspect(msg))
});
app.post('/', jsonParser, function (req, res) {
// Prepare output in JSON format
data = {
dev_id: req.body.dev_id,
pswd: req.body.password,
tx_cycle: req.body.tx_cycle
};
if (data.pswd != "password") {
console.log("Wrong password")
}
else {
console.log(data);
var topic = 'publish_topic';
var tx_cy = data.tx_cycle;
var msg = '{"port":"222","payload":"' + tx_cy + '","confirmed": false,"window":"BOTH","priority":0}';
console.log('Try to send downlink message, for ' + data.dev_id + ' set to ' + data.tx_cycle + ' min -> hex ' + tx_cy);
client.subscribe('reply/+/id/+');
client.publish(topic, msg);
res.status(200).send(msg + " sent to broker");
}
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
I solve the problem. The client id was refused by the broker because was not unique. Changing it solved the issue.