Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express router + WebSocketServer - sending message on POST

This is what I've got so far, and I'm trying to find a solution so that:

  • The connection is always kept alive, so I can handle status updates
  • I can send a websocket message to a client with data from the POST request

ws api here

 router.post('/', function (req, res) {
// Need to send ws.send() with post data
})


wss.on('connection', function(ws) {
  ws.on('message', function(message) {
    console.log('r : %s', message);
  });
  // ws is only defined under this callback as an object of type ws
});
like image 701
MNZT Avatar asked Dec 20 '22 02:12

MNZT


1 Answers

You can use event like this :

//Create an event
var event = require('events').EventEmitter();

router.post('/', function (req, res) {
   // fire an event
   event.emit('homePage')
})

wss.on('connection', function(ws) {
    ws.on('message', function(message) {
     console.log('r : %s', message);
    });

    // listen the event
    event.on('homePage', function(){
        ws.emit('someEvent');
    });
});
like image 147
Alexandre Avatar answered Jan 20 '23 23:01

Alexandre