'Websocket, listen and broadcast at the same time

Hello I'm trying to learn node.js, I'm a old PHP coder... The reason why I'm doing that is the websockets thing... so hard with PHP and natural with node... Anyway.. I'm so new with js and node I cannot figure how to do make this work together...

I have two example, they work perfectly separately but I cannot find away to use them both at the same time...

It very simple I want to listen to a websocket... process the data and send it to my own websocket/server

The server (work perfectly, so simple)

const server = new WebSocket.Server({ port: 8080 })
 
server.on('connection', serverSocket => {
  serverSocket.on('message', message => {
    console.log(`Received message => ${message}`);
  })
  serverSocket.send('Hello! Message From Server!!');
});

The client... (same here, so hard in PHP)

const client = new WebSocket('wss://stream.binance.com:9443/ws');
const msg = {
  method: 'SUBSCRIBE',
  params: ['btcusdt@miniTicker'],
  id: 1,
};

client.onopen = () => {
  client.send(JSON.stringify(msg));
};

client.onmessage = e => {
      const value = e.data;
      console.log(value);
      //// process the data...
      //// and send this data to my server, like serverSocket.send(value);
};

How I can use those 2 examples in the same node file/process. Again I'm so new... I did a lot of test with classes and async function and promises... with no good result most of the time I get the error

node:events:505
      throw er; // Unhandled 'error' event

But if I cannot make this work in the first place no use for me to learn the rest :O)

A big thank

Regards



Solution 1:[1]

I finally listen to Binance with a websocket, like I have in my example and I fix my issue by using socket.io to broadcast the processed data to my client.

This is the working example of my question.

const WebSocket = require('ws');
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

server.listen(8080, () => {
  console.log('listening on *:8080');
});

const client = new WebSocket('wss://stream.binance.com:9443/ws');
const msg = {
  method: 'SUBSCRIBE',
  params: ['troyusdt@miniTicker'],
  id: 1,
};

client.onopen = () => {
  client.send(JSON.stringify(msg));
};

client.onmessage = e => {
      const value = e.data;
      //console.log(value);
      io.emit('tokenUpdate', value); //// This is the part I was not able to do with websocket. the broadcast....
          
};

Regards

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1