0

This is my client-side code base. It is working with one of the exchange websockets but not working with this websocket. Any suggestions?

websocket reference: https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md

import React, { Component, createContext } from "react";

export const Contx = createContext();

export class ConProvider extends Component {
  state = {
    coins: [],
    digCoin: [],
    sou: [],
    passSocket: undefined
  };

  componentDidMount() {
    this.socketCall();  
  }

  socketCall = () => {
    var ws = new WebSocket("wss://stream.binance.com:9443");
    var msg = {
      "method": "SUBSCRIBE",
      "params": "btcusdt@depth",
      "id": 1
    };

    ws.onopen = () => {
      ws.send(msg);
    };

    ws.onmessage = e => {
      const value = e.data;
      this.setState({
        coins: value
      });
    };

    this.setState({
      passSocket: ws
    });
  };

  socketClose = () => {
    var wss = this.state.passSocket;
    wss.close();
  };

  render() {
    console.log(this.state.coins);

    // console.log(this.state.coins)
    return (
      <Contx.Provider
        value={{
          ...this.state,
          socketCall: this.socketCall,
          socketClose: this.socketClose
        }}
      >
        {this.props.children}
      </Contx.Provider>
    );
  }
}
4

2 回答 2

4
const ws = new WebSocket('wss://stream.binance.com:9443/ws');
const msg = {
  method: 'SUBSCRIBE',
  params: ['btcusdt@depth'],
  id: 1,
};

ws.onopen = () => {
  ws.send(JSON.stringify(msg));
};

Send accepts JSON format, I changed msg to object, passed the array to params and added /ws as mentioned above.

于 2020-03-29T23:27:16.460 回答
2

Try with

var ws = new WebSocket("wss://stream.binance.com:9443/ws");
于 2020-03-19T00:26:31.037 回答