3

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}`);
});

enter image description here

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

enter image description here

2
  • Did you try socket.io ? It could make it easier for you. Commented Nov 22, 2019 at 16:56
  • 1
    I'd rather work with rxjs and ws. I don't think they're hard, just that I might be missing a config or a detail at some point. Commented Nov 22, 2019 at 17:27

1 Answer 1

8
+50

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.