Maksym Popov
Maksym Popov

Reputation: 452

How to send ws message from route request

I've been trying to create an app that uses telegram-bot, express server and react app. Therefore, I need to create a POST request from telegram-bot to express, while express sends POST data to a websocket connection:

const express = require("express");
const app = express();
const expressWs = require("express-ws")(app);

// handles bot request
app.post("/request", (req, res) => {
  playlist.push(req.body.url);
  res.status(200).send({ message: "video is added to playlist" });
});

// after handling requst data must go here and send ws message to client side
app.ws("/echo", (ws, req) => {
  ws.on("message", msg => {
  ws.send(`msg is = ${msg}`);
  });
});

Am I making it right, and if so, how to call ws.send from after handling request at app.post route?

Upvotes: 2

Views: 2197

Answers (1)

Olawale Akinseye
Olawale Akinseye

Reputation: 177

From the understanding I have from your question, here is an updated version of your code that does exactly what you want.

I replaced the express-ws package with ws since that would be sufficient for your use case.

The express server runs on port 8080 while the websocket server runs on port 8081 since are different protocols and would not run on the same port (You can make it work but I do not recommend it See this question

const express = require("express");
const Websocket = require('ws');
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const wss = new Websocket.Server({ port: 8081 });

wss.on('connection', (ws) => {
  console.log('One client connected');
  ws.on("message", msg => {
    ws.send(`msg is = ${msg}`);
  });
})

// handles bot request
app.post("/request", (req, res) => {
  // Broadcast URL to connected ws clients
  wss.clients.forEach((client) => {
    // Check that connect are open and still alive to avoid socket error
    if (client.readyState === Websocket.OPEN) {
      client.send(url);
    }
  });

  res.status(200).send({ message: "video is added to playlist" });
});


app.listen(8080, () => {
  console.log('Express listening on 8080');
  console.log('Websocket on 8081');
});

Tested via curl with curl -d 'url=https://example.com/examplesong' localhost:8080/request I had a client connected to ws://localhost:8081 and everything looks good.

Upvotes: 5

Related Questions