I am trying to do a very simple websocket solution where, from a dotnet application, I send an integer to the socket and then from my rxjs I want to get that value.
Sending is very easy and I don't get any errors. So I guess the values are being sent (I use the Webpubsub in azure where I've created a client url from there):
But, receiving is not working at all. Nothing is happening. This copied directly from RxJS website:
The code inside that onInit is triggering first time the page loads but then nothing more.
In the browser, it looks like the hub is connected (in devtools I see that the hub is in pending mode which should be correct):
But, receiving is not working at all. Nothing is happening. This copied directly from RxJS website
WebsocketService
) to manage the WebSocket connection. This service will handle connecting, sending, and receiving messages.websocket.service.ts :
import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
const WS_ENDPOINT = 'wss://your-webpubsub-url'; // Replace with your actual Web PubSub URL
@Injectable({ providedIn: 'root' })
export class WebsocketService {
private ws: WebSocketSubject<any>;
constructor() {}
public connect(): void {
this.create();
}
private create() {
if (this.ws) {
this.ws.unsubscribe();
}
this.ws = webSocket<any>(WS_ENDPOINT);
this.ws.subscribe(); // Start listening for messages
}
public close() {
if (this.ws) {
this.ws.unsubscribe();
}
}
public sendMessage(message: any) {
this.ws.next(message);
}
}
WebsocketService
into the Angular components where you want to use WebSocket communication.messages$
observable to receive WebSocket messages. Handle incoming messages as needed.app.component.ts :
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { WebsocketService } from '../websocket.service'; // Adjust the path
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
})
export class YourComponent implements OnInit, OnDestroy {
private messagesSubscription: Subscription;
constructor(private websocketService: WebsocketService) {}
ngOnInit(): void {
this.websocketService.connect();
this.messagesSubscription = this.websocketService.messages$.subscribe({
next: (message: any) => {
console.log('Received message:', message);
// Handle the message as needed
},
error: (error: Error) => {
console.error('WebSocket error:', error);
},
complete: () => {
console.log('WebSocket connection closed');
},
});
}
ngOnDestroy() {
this.messagesSubscription.unsubscribe();
this.websocketService.close();
}
}
ngOnDestroy
).Connection status :
Receive messages :