1

I'm currently trying to understand NodeJS and express. Currently I want to send a message to the connected clients to my WebSocket when a POST request comes in via express. How can I do this?

This is my current code:

const WebSocket = require('ws').Server;
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const server = new WebSocket({
    server: app.listen(8181)
});

app.use(bodyParser.json());

server.on('connection', socket => {
    socket.on('message', message => {
        console.log(`received from a client: ${message}`);
    });
    socket.send('Hello world!');
});

app.post('/', function (req, res) {
    console.log(req.body.name);

    res.sendStatus(200);
});
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Mr. Jo
  • 4,946
  • 6
  • 41
  • 100

1 Answers1

1

You can declare a variable at top level, and then assign the connected sockets to it. Then use it to send messages to your clients. For example:

let ws = null;

server.on('connection', socket => {
  ws = socket;
  socket.on('message', message => {
    console.log(`received from a client: ${message}`);
  });
  socket.send('Hello world!');
});

app.post('/', function (req, res) {
  console.log(req.body.name);

  if (ws) ws.send('Welcome!');

  res.sendStatus(200);
});

Also, this might be working, but in general it doesn't serve right in real-world apps, where you want to scale and re-use! So I would recommend creating a singleton class for the socket. And use it in any place you want. Here I've a previous answer here which shows how it would look like.

Hope I've helped

MAS
  • 706
  • 1
  • 5
  • 14