简体   繁体   中英

Connect to a third party server (twelvedata) from my own express server through web socket connection string

I want to connect to the twelevedata server through its provided socket connection to receive information.


import * as dotenv from 'dotenv' 
import WebSocket from 'ws';
import express from 'express'

const app = express();

//setting up env
dotenv.config()

// setting up the websocket
const ws = new WebSocket(`wss://ws.twelvedata.com/v1/quotes/price?apikey=${process.env.API_KEY_TWELVEDATA}`);


const payload = {
  "action": "subscribe",
  "params": {
  "symbols": "AAPL,INFY,TRP,QQQ,IXIC,EUR/USD,USD/JPY,BTC/USD,ETH/BTC"
  },
}




ws.on('connection',function (steam) {

  ws.on('open', (data) => {
    console.log("data ==>",data);
    ws.emit('subscribe',payload)
  })
    
  ws.on('subscribe', (data) => {
    console.log("data ==>",data);
  })
})

const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`I am listening at ${port}`);
});

I created a websocket with my websocket connection on an express application but I am unable to receive any information from the twelvedata server regarding the subscribe event that I have emitted !

This is how the websocket should work as shown by the twelvedata website (look into the screen shots)

在此处输入图像描述 在此处输入图像描述

I am unable to connect and emit the subscribe event given by the twelvedata's documentation

You don't want to emit events from the websocket (that's for events you want to handle locally), but send , ie, replace

ws.emit('subscribe',payload)

with

ws.send(payload)

// sending the parameters
 ws.on('open', function open() {
    ws.send(JSON.stringify(payload));
  });
  
  ws.on('message', function message(data) {
    // receiving data
    console.log('data ===>: ', JSON.parse(data));
  });

ws.send did the charm for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM