Помочь разобраться с приложениям на websocket

Не могу понять, как запустить http сервер и слушать его с помощью сокетов

const WebSocket = require('ws');
const axios = require('axios');
const http = require("http");

class App {

  ws = {};
  heartbeat = {};
  ask;
  bid;

  constructor(ask, bid) {
  this.ask = ask;
  this.bid = bid;
  }

  getPublicWsToken = async function () {
    const baseURL = 'https://api.kucoin.com'
    const endpoint = `/api/v1/bullet-public`
    const url = baseURL + endpoint;
    const result = await axios.post(url, {});
    return result;
  }

  getSocketEndpoint = async function() {
    const r = await this.getPublicWsToken()

    const token = r.data.data.token;
    const instanceServer = r.data.data.instanceServers[0]

    if(instanceServer){
        return `${instanceServer.endpoint}?token=${token}&[connectId=${Date.now()}]`
    } else {
      throw Error("No Kucoin WS servers running")
    }
  }

  initSocket = async function () {

    try {
      
      const endpoint = `/market/level2:${this.bid},${this.ask}`;
      const topic = `/market/level2:${this.bid},${this.ask}`;
      const type = 'public';

      let websocket = await this.getSocketEndpoint()
      const ws = new WebSocket(websocket); // Здесь как 
      this.ws[topic] = ws;
      console.log(this.ws)
      ws.on('open', () => {
        console.log(topic + ' opening websocket connection... ');
        this.subscribe(topic, endpoint, this.eventHandler);
        this.ws[topic].heartbeat = setInterval(() => (this.socketHeartBeat, 20000, topic));
      })
      ws.on('error', (error) => {
        this.handleSocketError(error);
        console.log(error);
      })
      ws.on('ping', () => {
        return
      })
      ws.on('close', () => {
        clearInterval(this.ws[topic].heartbeat)
        console.log(topic + ' websocket closed...')
      })
    } catch(err) {
      console.log(err)
    }
    
  }

  handleSocketError = function (error) {
  console.log('WebSocket error: ' + (error.code ? ' (' + error.code + ')' : '') +
  (error.message ? ' ' + error.message : ''))
  }

  socketHeartBeat = function(topic) {
    console.log(this.ws)
    let ws = this.ws.topic
    ws.ping()
  }

  subscribe = async function(topic, endpoint, eventHandler) {
    let ws = this.ws[topic]
  
    ws.send(JSON.stringify({
      id: Date.now(),
      type: 'subscribe',
      topic: endpoint,
      response: true
    }))
    
    ws.on('message', eventHandler)
  }

  unsubscribe = async function(topic, endpoint, eventHandler) {
    let ws = this.ws[topic]
    ws.send(JSON.stringify({
      id: Date.now(),
      type: 'unsubscribe',
      topic: endpoint,
      response: true
    }))
    ws.on('message', eventHandler)
  }

  eventHandler = function () {
    console.log('work');
  }
}


const app = new App('BTC','USDT')

app.initSocket();


Ответы (0 шт):