下面是一个使用Angular和RxJS的WebSocket示例:
npm install --save rxjs webstomp-client
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { filter, map, retryWhen, switchMap } from 'rxjs/operators';
import * as Stomp from 'webstomp-client';
@Injectable({ providedIn: 'root' })
export class WebSocketService {
private stompClient: Stomp.Client;
constructor() { }
connect(url: string): Observable {
return new Observable((observer) => {
this.stompClient = Stomp.client(url);
this.stompClient.connect({}, (frame) => {
observer.next(frame);
this.stompClient.subscribe('/topic/messages', (message) => {
observer.next(message);
});
});
}).pipe(
retryWhen(errors => errors.pipe(
switchMap(error => {
console.log('WebSocket connection lost. Reconnecting...');
this.stompClient.disconnect();
return this.connect(url);
})
))
);
}
sendMessage(destination: string, body: string): void {
this.stompClient.send(destination, {}, body);
}
}
export class AppComponent implements OnInit {
messages$: Observable;
constructor(private webSocketService: WebSocketService) { }
ngOnInit() {
const url = 'ws://localhost:8080/ws'; // WebSocket服务器URL
this.messages$ = this.webSocketService.connect(url).pipe(
filter((message) => message && message.body),
map((message) => message.body)
);
}
sendMessage() {
const destination = '/app/sendMessage'; // 发送消息的目标地址
const body = 'Hello, WebSocket!'; // 消息正文
this.webSocketService.sendMessage(destination, body);
}
}
{{ message }}
请注意,以上代码示例假设您已经在WebSocket服务器上设置了适当的端点和订阅器。您需要根据实际情况进行调整。