John Doe
John Doe

Reputation: 1172

websocket request with nodeJS

I am trying to initiate a websocket request using nodeJS. I am new to WS, and I am quite stuck with this, and all examples I could find seem to be the same one with building a chat, repeated over and over in every media lol, and it didn't help me better understand.

I have an API that provides real-time data (forex). I am able to successfully subscribe to sources of real-time data on the front-end, and do what I want. BTW, I don't get any CORS issue doing that, for some reason I don't understand.... :-o

However, i'd like to get this real-time data through my server, so my API key doesn't appear clearly.

So, I want to initiate a request to my server; this request open a channel to the supplier of forex data's API. Then I open a channel to receive this real-time data from my server. I have thought of the following, but that doesn't work.

var enableWs = require('express-ws');
enableWs(app);
const WebSocket = require('ws');
const WebSocketServer = require('ws').Server;
const URL = 'wss://API_ENDPOINT?api_key=MY_KEY';

app.ws('/ws', function (ws, req) {
  const wss = new WebSocket(URL);
  let msg = { action: 'subscribe', symbol : 'EUR-USD'};

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

  wss.onmessage = function (event) {
    jsonData = JSON.parse(event.data);
    
    // now, i want to send the RT data received in jsonData to another channel so I can display the data on the FE
    const wssReact = new WebSocketServer({ port: 7100 });
    wssReact.send(jsonData);
  }

  wss.onclose = function (event) {
    wss.terminate();
  };
});

On the front-end, I expected to get a result when opening a socket as follows :

const socket = new WebSocket('ws://localhost:7100');

Upvotes: 0

Views: 3766

Answers (2)

Muhammad Moeez Raza
Muhammad Moeez Raza

Reputation: 1

const express = require('express');
const enableWs = require('express-ws');
const WebSocket = require('ws');

const app = express();
const wss = new WebSocket.Server({ noServer: true });

// Handle WebSocket upgrade requests
app.get('/ws', (req, res) => {
  wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onWebSocketConnect);
});

function onWebSocketConnect(ws) {
  const msg = { action: 'subscribe', symbol: 'EUR-USD' };

  ws.on('message', function (message) {
    // When the client sends a message, you can process it here if needed.
  });

  ws.on('close', function () {
    // Clean up resources related to this connection if needed.
  });

  // Connect to the forex data API
  const forexApiWebSocket = new WebSocket(URL);

  forexApiWebSocket.on('open', () => {
    forexApiWebSocket.send(JSON.stringify(msg));
  });

  forexApiWebSocket.on('message', function (event) {
    const jsonData = JSON.parse(event);
    
    // Send the received real-time data to the connected client
    ws.send(JSON.stringify(jsonData));
  });

  forexApiWebSocket.on('close', function () {
    // Handle the forex data API connection closed, if needed.
  });
}

// Start your server
const port = 7100;
const server = app.listen(port, () => {
  console.log(`WebSocket server listening on port ${port}`);
});

Upvotes: 0

John Doe
John Doe

Reputation: 1172

ok, I figured how to do what i wanted to achieve. I was close :-) And now it seems obvious lol.

My incoming WS data from the data provider is inconsistent, that's one reason why I couldn't figure the solution earlier.

app.ws('/ws', function (ws, req) {
  const wss = new WebSocket(URL);
  let msg = { action: 'subscribe', symbol : 'EUR-USD'};

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

  wss.onmessage = function (event) {
    ws.send(event.data);
  }

  wss.onclose = function (event) {
    wss.terminate();
  };
});

I hope it can be of any help to someone else :)

Upvotes: 0

Related Questions