Angular 9 RxJs Websockets / WebSocketSubject not recieving message from server

Viewed 5407

I am using Angular 9 and I'm trying to get rxjs websocket to work so first I've created a simple nodejs server that recieves and sends a message.

Here is the code for the server:

// server.js

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8000 })

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  })
  ws.send('Hello! Message From Server!!')
})

Now for the client part I'm using Angular 9 and Rxjs websockets.

So here is the code for app.component.ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  myWebSocket: WebSocketSubject<any> = webSocket('ws://localhost:8000');

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

  sendMessageToServer() {
    this.myWebSocket.next({message: 'some message'});
  }

}

And finally the html on app.component.html:

<button (click)="sendMessageToServer()">Send Message To Server</button>

My issue is that when I send the message via "sendMessageToServer()" the server will recieve it, so the comunication from Client to Server is working fine but the console is not showing the message that the server returns back:

Hello! Message From Server!!

Why is this happening? How can I fix this?

1 Answers

rxjs/webSocket is handling every message as valid JSON string, so you need to send from server also valid JSON string. To do that simply use JSON.stringify() like this:

wss.on('connection', ws => {
  console.log('new connection');
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  })
  ws.send(JSON.stringify('Hello! Message From Server!!'));
});

On the client side you don't need to do nothing

Expected output: enter image description here

UPDATE Also you can override serializer and deserializer of WebSocketSubjectConfig with own methods like in this example

Related