1

I have Nodejs server hosted on CPanel. This server runs for something like 1 hour to 3 hours before stopping. I am using version 14.21.2 of Nodejs.

Below is my code:

const express = require("express");
const WebSocketServer = require('ws');
const WebSocket = require('ws');

var admin = require("firebase-admin");
var serviceAccount = require("somejson.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://somedatabase.firebaseio.com"
});


var reconnectInterval = 1000 * 10;

//connect to twelve
var rootRef = admin.database().ref();
var p = 0;

function connect() {
    const ws2 = new WebSocket("wss://ws.somedomain.com/v1?apikey=someapikey");

    ws2.addEventListener("open", () => {
        ws2.send('{ "action": "subscribe", "params": { "symbols": "AANF" } }');
        
    });

    ws2.addEventListener("close", (eve) => {
        //
        setTimeout(connect, reconnectInterval)
    });
    
    ws2.addEventListener("error", (err) => {
        //
        console.log("Error: " + err.code);
    });

    ws2.addEventListener('message', function(event) {
        var received_msg = JSON.parse(event.data);

        p = received_msg["p"];

        if (p > 0) {
            
            rootRef.child("Xeex").child("Data").child("p").set(p);

        }

    });


}

//start socket
connect();


//
var http = require('http');
var server = http.createServer(function(req, res) {

    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });

    var message = 'The server is running...\n',
        version = 'NodeJS ' + process.versions.node + '\n',
        response = [message, version].join('\n');
    res.end(response);
    
});
server.listen();

So let me break this down into parts and steps: When I create this Nodejs application on CPanel and click the start app button, the Websocket ws2 is not triggered, as I thought it should open connection instantly when the app started. How do I know that the ws2 is not triggered? If I check my firebase database nothing is updating, so to trigger this ws2 I have to open the URL where the app is hosted in a browser: ie.

www.myapp.mydomain.com.

If I open this link on a browser the ws2 start working as it receives data from API and post it to my firebase. So that brings in my first question that is:

How can I set up this code correctly such that if I start the app from CPanel the ws2 start working automatically without me having to load the link on a browser.

Second issue: When the ws2 starts working is working for about 1 to 3 hours before stopping. After something like 3 hours no updates will be posted to my firebase, that would mean the Websocket ws2 has disconnected or something, but I tried to set a reconnection like this:

ws2.addEventListener("close", (eve) => {
        //
        setTimeout(connect, reconnectInterval)
    });

which does not seem to work. I also tried to check if there is any error occurring as follows:

ws2.addEventListener("error", (err) => {
        //
        console.log("Error: " + err.code);
    });

But nothing in log is showing as error. I also tried to contact API provider thinking that maybe the problem might be from their servers but their response was clearly not what I thought as thing work well from their side.

So as far as I tried, I am thinking that it is probably poor coding, maybe there is something missing in my code, because I do not get any error code at all.

I even checked from CPanel to check if the app is running or has stopped, surely it is running from that side. So to restart this server after it stops, I have to reload the server URL in a browser to kick start it, once I have done that it runs for about 1hour or so then stops again.

So that brings my second question as how to correct my code so that my server runs without stopping?

NOTE: This problem also happens when I run the server on my local machine through command prompt (cmd) it stops receiving data from API after 1 hour or so without any error!

Wahlstrommm
  • 684
  • 2
  • 7
  • 21
tinoe
  • 216
  • 2
  • 11
  • looks like node keeps running but the websockets fail, maybe the websockets have a seperate log? – john Smith Apr 27 '23 at 07:40
  • There is nothing in log unfortunately – tinoe Apr 27 '23 at 07:43
  • yeah AFAIS you have to manually log it, sth like here https://stackoverflow.com/questions/46670883/proper-error-handling-on-the-node-js-ws-package – john Smith Apr 27 '23 at 07:44
  • I get you, but I have another app which does not have Websocket, it has an Interval which posts current timestamp to firebase as well it stops the same way. If you look at the structure of my code is it correct? Why does it not trigger the function connect when I start the app from CPanel? – tinoe Apr 27 '23 at 07:48
  • Besides making sure your code is working correctly, you should really be using something like [PM2](https://pm2.keymetrics.io/) – Richard Dunn Apr 27 '23 at 08:04
  • How does this help on a app deployed on CPanel? – tinoe Apr 27 '23 at 08:08

0 Answers0