简体   繁体   English

使用带有webpack的socket.io连接到GDAX websocket api

[英]Connecting to GDAX websocket api using socket.io with webpack

I want to connect to the GDAX websocket api with an in browser application built with react and webpack. 我想使用用react和webpack构建的浏览器应用程序连接到GDAX websocket api。 I cannot use the offiicial gdax-node or gdax-toolkit api's because they are not compatible with webpack. 我不能使用官方的gdax-node或gdax-toolkit api,因为它们与webpack不兼容。 I decided to try connecting to the websocket myself using socket.io, but the code below never establishes a connection. 我决定尝试使用socket.io自己连接到websocket,但是下面的代码从未建立连接。 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 };

Socket.io is not the appropriate library to use for this. Socket.io不适合用于此。 I switched it to using global's websocket and it works fine. 我将其切换为使用global的websocket,并且工作正常。

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

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. 由于gdax仅将wss URL公开给了公众,而socket.io不支持wssws连接,因此我们必须找到解决方法。 Here global.websocket is enough to make connection in the browser. 在这里global.websocket足以在浏览器中建立连接。 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 . 它只是包装了ws软件包,当您使用webpack构建供浏览器使用时,它将用browser.js替换main。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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