Подключение WebSocket в Angular - PullRequest
0 голосов
/ 31 марта 2020

У меня есть WebSocket Connection в узле, который работает нормально. Теперь я хочу использовать его в Angular с веб-сокетом rx js, но я не знаю, как решить соединение.

const WebSocket = require('ws');

const ws = new WebSocket('wss://example.com');


ws.on('open', function open() {
  // on connection, send our authentication request
  ws.send(JSON.stringify({action: 'auth', key: apiKey, secret: apiSecret}));  
});

ws.on('close', function close() {
  console.log('disconnected');
});

ws.on('message', function incoming(data) {
  console.log(data)
  var msg = JSON.parse(data);
  if (msg.type === 'status' && msg.status === 'authenticated') {
    // if we got authentication confirmation, send subscribe event to the server
    ws.send(JSON.stringify({action: 'subscribe', buckets: ['exampleBucket']}));
  }
});

Ответы [ 2 ]

0 голосов
/ 31 марта 2020
export class SocketsService {
  ws: any;
  messages: Subject<any>;
  private connectionSubject: Subject<MessageEvent>;

  constructor(
    @Inject('wsServerUrl') private wsUrl : string
  ) {
    this.initConnection();
  }

  public initConnection() {
    this.messages= new Subject<any>();

    this.connectionSubject = this.wsCreate(this.wsUrl);

    if (typeof this.ws!== 'undefined' && this.ws.readyState !== 0 && this.ws.readyState !== 1) {
      this.connectionSubject = this.wsCreate(this.wsUrl);
    }

    this.ws.onmessage = e => {
      const response = e.data;
      return this.orders.next(response);
    };

    this.ws.onclose = e => console.log('client disconnected ');
  }

  send(value: string) {
    this.ws.send(value);
  }

  closeConnection() {
    this.ws.close(1000, 'disconnect');
    this.ws = undefined;
  }

  private wsCreate(url): Subject<any> {
    this.ws= new WebSocket(url);
    const observable = new Observable((obs: Observer<string>) => {
      this.ws.onmessage = obs.next.bind(obs);
      this.ws.onerror = obs.error.bind(obs);
      this.ws.onclose = obs.complete.bind(obs);
      return this.ws.close.bind(this.ws);
    });

    const observer = {
      next: (data: object) => {
        if (this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify(data));
        }
      }
    };

    return Subject.create(observer, observable);
  }
}

используя тему, вы можете подписаться на сообщения в любом компоненте. Чтобы создать соединение, вам нужно внедрить этот сервис в компонент (например, app.component). Затем вы можете отправлять сообщения, используя отправить метод обслуживания

прослушивать сообщения в компоненте:

this.subscription = this.socketsService.messages.subscribe((message: string) => {
    // do something
});
0 голосов
/ 31 марта 2020

Прослушивание сообщений с сервера

import { webSocket } from "rxjs/webSocket";
const subject = webSocket('wss://example.com');

subject.subscribe(
   msg => console.log('message received: ' + msg), // Called whenever there is a message from the server.
   err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
   () => console.log('complete') // Called when connection is closed (for whatever reason).
 );

Отправка сообщений на сервер

import { webSocket } from "rxjs/webSocket";
const subject = webSocket('wss://example.com');

subject.subscribe();
// Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
// since no connection was established!

subject.next({message: 'some message'});
// This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!

subject.complete(); // Closes the connection.

subject.error({code: 4000, reason: 'I think our app just broke!'});
// Also closes the connection, but let's the server know that this closing is caused by some error.
...