我通过websockets连接到Spring-Boot服务器,以接收特定设备的日志。
logsStompConfig.ts
import { StompConfig } from '@stomp/ng2-stompjs';
import * as SockJS from 'sockjs-client';
export const logsStompConfig: StompConfig = {
url: () => new SockJS('http://localhost:9000/gs-guide-websocket'),
headers: {},
heartbeat_in: 0,
heartbeat_out: 20000,
reconnect_delay: 1000,
debug: false
};
logs.service.ts
import { Injectable } from '@angular/core';
import { StompService } from "@stomp/ng2-stompjs";
import { Message } from "@stomp/stompjs";
import { Observable } from "rxjs/Observable";
@Injectable()
export class LogsService {
private stomp_subscription: Observable<Message>;
constructor(private stompService: StompService) {
this.stomp_subscription = stompService.subscribe('/topic/logs');
}
connect(uuid: string) {
this.stompService.publish('/app/ws', JSON.stringify({uuid}));
return this.stomp_subscription.map((message: Message) => message);
}
}
logs.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import { Message } from "@stomp/stompjs";
import { LogsService } from "logs.service";
@Component({
selector: 'logs',
templateUrl: 'logs.component.html',
styleUrls: ['./logs.component.scss']
})
export class LogsComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private logsService: LogsService) {}
ngOnInit() {
this.subscription = this.logsService.connect('666-771').subscribe(message => {
console.log(message);
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
logs.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { StompService, StompConfig } from "@stomp/ng2-stompjs";
import { logsStompConfig } from "./logsStompConfig";
import { LogsService } from "./logs.service";
import { LogsComponent } from './logs.component'
@NgModule({
imports: [
CommonModule
],
declarations: [LogsComponent],
providers: [
StompService,
{
provide: StompConfig,
useValue: logsStompConfig
},
LogsService
],
exports: [LogsComponent]
})
export class LogsModule { }
根据chrome devtools,我多次发布而不是一次,因此在客户端上获取重复条目。
我错过了一些参数或什么? 有趣的是,Spring https://spring.io/guides/gs/messaging-stomp-websocket/的指南给出了同样奇怪的结果。