使用nodeJS的WebSocket请求

llycmphe  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(112)

我正在尝试使用nodeJS发起WebSocket请求。我是WS的新手,我很坚持这一点,我能找到的所有例子似乎都是建立聊天的同一个例子,在每个媒体LOL中一遍又一遍地重复,这并没有帮助我更好地理解。
我有一个API,提供实时数据(外汇)。我能够成功地订阅前端的实时数据源,并做我想做的事情。顺便说一句,我没有得到任何CORS问题这样做,出于某种原因,我不明白....:-o
然而,我想通过我的服务器获取这些实时数据,所以我的API密钥不会清楚地显示出来。
所以,我想向我的服务器发起请求;这个请求打开了一个通道到外汇数据的API的供应商。然后,我打开一个通道,从我的服务器接收这些实时数据。我想到了下面的办法,但那不起作用。

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();
  };
});

字符串
在前端,我期望在打开socket时得到如下结果:

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

5gfr0r5j

5gfr0r5j1#

好吧,我想好了怎么做我想做的事。我很接近:-)现在看来很明显,哈哈。
我从数据提供程序传入的WS数据不一致,这是我之前无法找到解决方案的原因之一。

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();
  };
});

字符串
希望能对其他人有所帮助:)

tvz2xvvm

tvz2xvvm2#

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}`);
});

字符串

相关问题