Connecting to GDAX websocket api using socket.io with webpack

让人想犯罪 __ 提交于 2019-12-25 02:00:57

问题


I want to connect to the GDAX websocket api with an in browser application built with react and webpack. I cannot use the offiicial gdax-node or gdax-toolkit api's because they are not compatible with webpack. I decided to try connecting to the websocket myself using socket.io, but the code below never establishes a connection. In the code below my "subscribing" log message after connect never appears. How do I get this code to connect or at least show an error message?

const io = require('socket.io-client');

var subscribe = {
  "type": "subscribe",
  "channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]
};

function subscribeToTimer(cb) {
  console.log('Opening socket');
  var socket = io.connect('wss://ws-feed.gdax.com');

  socket.on('connection', function(socket) {
    console.log('Subscribing');

    socket.on('disconnect', function(socket) {
      console.log('Clinet disconnected.');
    });    
  });

  //socket.on('message', timestamp => cb(null, timestamp));
  socket.on('message', data => { console.log(data); });
  socket.on('error', data => { console.log(data); });
}
export { subscribeToTimer };

回答1:


Socket.io is not the appropriate library to use for this. I switched it to using global's websocket and it works fine.

function subscribeToTimer(cb) {
  console.log('Opening socket');
  const socket = new WebSocket('wss://ws-feed.gdax.com');

  socket.addEventListener('message', function(event) {
    console.log('new message', event.data);
  });

  socket.addEventListener('open', function(event) {
    console.log('Subscribing');


    var subscribe = '{"type": "subscribe", "channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]}';
    socket.send(subscribe);

    socket.addEventListener('close', function(event) {
      console.log('Client disconnected.');
    });    
  });

  //socket.addEventListener('message', timestamp => cb(null, timestamp));
}



回答2:


Since gdax only exposed the wss url to public and socket.io does not support wss or ws connection, we have to find work around. Here global.websocket is enough to make connection in the browser. Or you could also check out this library. It simply wraps the ws package and when you build by webpack for browser usage, it will replace the main by browser.js.



来源:https://stackoverflow.com/questions/48835447/connecting-to-gdax-websocket-api-using-socket-io-with-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!