【发布时间】:2017-03-05 23:28:04
【问题描述】:
我正在使用angular2-websocket 包装器。虽然我没有关闭websocket,但是当我稍后尝试发送消息时,我得到一个错误,说websocket已经关闭了。
我的组件如下所示。
export class ListDataComponent implements OnInit, OnDestroy, AfterViewInit {
ws: $WebSocket;
sub: Subscription;
ngAfterViewInit() { this.initWebSocket(); }
ngOnDestroy() { this.destroyWebSocket(); }
initWebSocket(): void {
this.ws = new $WebSocket('ws://localhost:8080/topic/data');
this.sub = this.ws.getDataStream().subscribe(
data => {
console.log(data);
//this part is following the example on the github page
//makes me unsure because the close method will force a close and true/false only signifies if the closing is immediate or not
//even if i comment out this line, i still get the same behavior
this.ws.close(false);
},
err => console.err(data)
);
}
destroyWebSocket(): void {
//this is the only place where i destroy/release my websocket resources
if (this.sub) {
try {
this.sub.unsubscribe();
} catch(err) { }
}
if (this.ws) {
try {
this.ws.close(true);
} catch(err) { }
}
}
//this method is bound to a bunch of checkboxes that triggers sending data back to the websocket topic
selectionChanged(i: number): void {
let json = getSomeJson(i); //gets some JSON to send back; omitted
this.ws.send(json).subscribe(
data => console.log(data),
err => {
//it seems i can't send because the websocket has been closed! why?
console.error(err);
}
);
}
}
查看 JavaScript 控制台,我看到以下消息。
套接字连接已关闭 (匿名)@list-data-ws.component.ts:141 SafeSubscriber.__tryOrSetError@Subscriber.js:243 SafeSubscriber.error@Subscriber.js:199 订阅者._error@订阅者.js:128 订阅者.error@订阅者.js:102 (匿名)@ angular2-websocket.js:123 Observable._trySubscribe@Observable.js:57 Observable.subscribe@Observable.js:45 webpackJsonp.362.ListTransactionWsComponent.cryptoSelected@list-transaction-ws.component.ts:139 View_ListTransactionWsComponent1.handleEvent_2 @ /AppModule/ListTransactionWsComponent/component.ngfactory.js:68 (匿名)@view.js:664 (匿名)@ dom_renderer.js:489 webpackJsonp.946.ZoneDelegate.invokeTask@zone.js:363 onInvokeTask@ng_zone.js:264 webpackJsonp.946.ZoneDelegate.invokeTask@zone.js:362 webpackJsonp.946.Zone.runTask@zone.js:166 ZoneTask.invoke奇怪的是,我仍然不断地在数据流中返回数据。我还在后端(Spring Boot)放置了调试消息,我没有看到 websocket 已关闭。
如果有帮助的话,
- 我的前端使用 Angular 2 和 angular-cli v1.0.0-beta.32.3 和
- 我的后端使用的是 Spring Boot v1.5.1
【问题讨论】:
标签: angular websocket spring-websocket