Search code examples
node.jswebsocketserverclient

How to send websocket message to client from the serverside


Hello I have two backends laravel and Nodejs and There will be one frontend.

So if the front end requests something on laravel and laravel requests to node and Node has to send a message to the client through WebSocket. How to do It?

Index.js

const app = require('express')();
const http = require('http');
const WebSocket = require('ws')

//initialize a simple http server
const server = http.createServer(app);
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
});
let sendNotification;
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
let socketapi = require('./socketapi')
socketapi.start(wss)
//start our server
server.listen(process.env.PORT || 5555, () => {
    console.log(`Server started on port ${server.address().port} :)`);
});

socketapi.js

module.exports ={
    start: (wss) => {
        wss.on('connection', (ws) => {
            console.log('connected!!!');
            console.log(socketIds)
            //connection is up, let's add a simple simple event
            // triggerMessage('data');
            ws.id=uuidv4()
            ws.on('message', (message) => {
                console.log('received: %s', message);
                // ws.send(`Hello, you sent -> ${message}`);
            });
        }
    }
 }

Now I want to use this socket in the controller file and send it as I get a request.

When I export and import socket it logs as undefined.


Solution

  • I have stored and ws in array with particular Id and that Id was associated with data in DB so I can use that Id to get ws and send through that ws on function calling