is it not possible to send updates or message to your server(node.js) from your server(node.js) websocket instance?

24 Views Asked by At

This is a question out of pure curiosity, although I tried doing this many times but it seems not possible, in order to send any update(publish, send message etc..) to your server you need to have a socket connection for that, and the server(listener) in this case cannot act as a connection / client as per my knowledge, I want to know if there is any possible way to achieve this, one way I can think of is using the in built events of node.js, which seems doable but generally with web socket is it possible? for better understanding I will be attaching some code snippets below.

Inside webhook.js you can find my websocket trying to send a webhook update but it cannot since that method requires the property wsConnection which is not initiated.

I have already referred to this particular question infact I took the approach from this question only. NodeJS + WS access currently running WS server instance

websocket.js

const crypto = require('crypto');

class WebSocketManager {
    constructor() {
        this.wsConnection = null;
        this.init();
    }

    init() {
        uWs.App().ws('/*', {
            compression: uWs.SHARED_COMPRESSOR,
            maxPayloadLength: 16 * 1024 * 1024,
            idleTimeout: 10,
            open: (ws) => {
                ws.id = crypto.randomBytes(6).toString("hex");
                this.wsConnection = ws;
                console.log('A user connected');
            },
            message: (ws, message, isBinary) => {
                this.messageFunction(ws, message);
            },
            drain: (ws) => {
                console.log('WebSocket backpressure: ' + ws.getBufferedAmount());
            },
            close: (ws, code, message) => {
                console.log('WebSocket closed');
            }
        }).listen(3000, (token) => {
            if (token) {
                console.log('webscoket server Listening to port ' + 3000);
            } else {
                console.log('Failed to listen to port ' + 3000);
            }
        });
    }

    messageFunction(ws, message) {
        let data = JSON.parse(Buffer.from(message).toString());
        if (data.type === 'join') {
            console.log(`room joined by ${ws.id} roomid => ${data.chatRoomId}`);
            ws.subscribe(data.chatRoomId);
            ws.currentRoom = data.chatRoomId;
        } else if (data.type === 'send-message') {
            console.log('message received:', 'chatroomId', data.chatRoomId, "mesage => ", data.message);
            ws.publish(data.chatRoomId, JSON.stringify({ type: 'emit-to-client', message: data.message }));
        } else if (data.type === 'login') {
            console.log('User logged in:', data.user);
            ws.publish('userLoggedIn', JSON.stringify(data.user));
        } else if (data.type === 'logout') {
            console.log('refresh user list');
            ws.publish('refreshUsers', JSON.stringify(data.user));
        }
        else if (data.type === 'paymentIntent') {
            console.log('payment socket update received')
        }
    }

    sendWebHookUpdate(message) {
        if (this.wsConnection) {
            this.wsConnection.publish('paymentIntent', JSON.stringify({ type: 'paymentIntent', message: message }));
        } else {
            console.log('No WebSocket connection');
        }
    }
}

module.exports = WebSocketManager;

app.js


const webHookRoutes = require('./helpers/webhooks');
const notifierService = require('./controllers/ws');
let notifier = new notifierService();
notifier.connect(server);
let UwsManager = new wsManager();
UwsManager.init();
app.use(webHookRoutes(notifier)); 

webhook.js


const express = require('express');
const router = express.Router();
const webSocketManager = require('../controllers/uwebsocketclass');
require('dotenv').config();
module.exports = (webSocket) => {
    router.post('/webhook', async (req, res) => {
        // Return a response to acknowledge receipt of the event
        webSocket.sendWebHookUpdate(req.body);
        res.json({ received: true });
        ;
    })
    return router;

}

0

There are 0 best solutions below