Can't read websocket on angular

怎甘沉沦 提交于 2020-01-30 05:45:11

问题


I am trying to exchange info through websockets between an Angular 8 app and a simple server. Strangely I'm able to send info to the server, but I can't seem to find how to wire the app to receive back my echoes.

Here's the app component :

import { Component } from '@angular/core';
import { webSocket, WebSocketSubject } from "rxjs/webSocket";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  ws : WebSocketSubject<any>;

  ngOnInit() {}

  constructor() {
    this.ws = webSocket('ws://localhost:8999');
    this.ws.subscribe({
      next : (data) => console.log(`Received ${data}`),
      error : (err) => {},
      complete : () => {}
    });
  }

  buttonClick() {
    this.ws.next("test");
  }

}

Here's the server :

import * as express from 'express';
import * as http from 'http';
import * as WebSocket from 'ws';

const server = http.createServer(express());

const wss = new WebSocket.Server({ server });

wss.on('connection', (ws: WebSocket) => {
    // Print and echo
    ws.on('message', (data) => {
      console.log(`received: ${data}`);
      ws.send(`echo: ${data}`);
    })
});

setInterval(() => wss.clients.forEach(ws => ws.send(`ping!`)), 2000);


// Start server
server.listen(process.env.PORT || 8999, () => {
    console.log(`Server started on port ${(<WebSocket.AddressInfo>server.address()).port}`);
});

And testing the server with a simple tool at least confirms me that side is working


回答1:


You don't get any errors because you skip all the errors by using empty error callback:

this.ws.subscribe({
  next : (data) => console.log(`Received ${data}`),
  error : console.log, <==================================== add this
  complete : () => {}
});

Once you log the errors you should get something like:

SyntaxError: Unexpected token p in JSON at position 0 at JSON.parse ()

This seems that the response from your websocket wasn't handled properly. That's because rxjs expects json but you're sending plain string. Websocket implementation from rxjs uses default configuration as follows:

const DEFAULT_WEBSOCKET_CONFIG: WebSocketSubjectConfig<any> = {
  url: '',
  deserializer: (e: MessageEvent) => JSON.parse(e.data),
  serializer: (value: any) => JSON.stringify(value),
};

How should it be fixed?

You can either send json from server or provide custom deserializer:

this.ws = webSocket({
  url: 'ws://localhost:8999',
  deserializer: e => e.data
});


来源:https://stackoverflow.com/questions/58926375/cant-read-websocket-on-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!