我正在尝试使用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');
型
2条答案
按热度按时间5gfr0r5j1#
好吧,我想好了怎么做我想做的事。我很接近:-)现在看来很明显,哈哈。
我从数据提供程序传入的WS数据不一致,这是我之前无法找到解决方案的原因之一。
字符串
希望能对其他人有所帮助:)
tvz2xvvm2#
字符串