简体   繁体   中英

How can subscribe to ws websocket from a nodejs server to another server?

I have microservice in nodejs that must subscribe to ws (not socket.io) websocket written in c# (you can consider any language here) , please offer snippet or document for read or anything else that show how do this (not functional, with oop classes style ).

where must subscribe to messages in class and what syntax is like?

i tried millions way but you have to implement it with raw 'ws' when listen on others server in nestjs.

// -------------------- Packages ------------------

import { InjectQueue } from '@nestjs/bull';
import { Inject, Injectable, Logger } from '@nestjs/common';
import * as WebSocket from 'ws';

// ------------------------------------------------

@Injectable()
export class SocketService {
  // -------------------- LGGER --------------------------

  private logger = new Logger(SocketService.name);

  // ------------------- Filelds and Props ---------------

  private readonly routeForSocket = 'wss://yourSenderAddressMaybeIsC#orJAVA';
  private socketRLC: WebSocket;

  // ------------------- Ctor ---------------

  constructor() {
    this.onRLCSocketClose = this.onRLCSocketClose.bind(this);
    this.onRLCSocketError = this.onRLCSocketError.bind(this);
    this.onRLCSocketOpen = this.onRLCSocketOpen.bind(this);
    this.onRLCSocketMessage = this.onRLCSocketMessage.bind(this);
  }

  // =================== INIT SOCKET  ========================

  public initSocketRLC(rlcToken: string) {
    this.socketRLC = new WebSocket(this.routeForSocket,'token-if-need');
    this.socketRLC.onopen = this.onRLCSocketOpen;
    this.socketRLC.onerror = this.onRLCSocketError;
    this.socketRLC.onmessage = this.onRLCSocketMessage;
    this.socketRLC.onclose = this.onRLCSocketClose;
  }

  // SOCKET Listen On Open --------------------------------------------

  public async onRLCSocketOpen(msg) {
    console.log(msg);
    if (msg.type === 'open') {
      console.log('hellow');
    }
  }

  // SOCKET Listen MESSAGE HANDLER ------------------------------------------

  public async onRLCSocketMessage(msg: any) {
    const msgArr = msg.data.split(',');
    // console.log(msgArr, 'i am messagesssssssssssssssssssssss');
   
  }

  // SOCKET Listen ERROR HANDLER --------------------------------------------

  public onRLCSocketError(error: any)
    console.log(error, 'i am error');
  }

  // SOCKET Listen CLOSE HANDLER --------------------------------------------

  public async onRLCSocketClose(cmp: any) {
    console.log(cmp);
  }

  // SOCKET CLOSE BY FORCE --------------------------------------------------

  public async closeRLC(): Promise<any> {
    this.socketRLC.close();
  }
}

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