Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't read websocket on angular

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

like image 860
VincentDM Avatar asked Jul 03 '26 10:07

VincentDM


1 Answers

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
});
like image 168
yurzui Avatar answered Jul 06 '26 02:07

yurzui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!