首页 文章

为什么我的Angular 2应用程序中的Web套接字已关闭,尽管我没有明确关闭它?

提问于
浏览
0

我正在使用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控制台,我看到以下消息 .

Socket connection has been closed
(anonymous) @   list-data-ws.component.ts:141
SafeSubscriber.__tryOrSetError  @   Subscriber.js:243
SafeSubscriber.error    @   Subscriber.js:199
Subscriber._error   @   Subscriber.js:128
Subscriber.error    @   Subscriber.js:102
(anonymous) @   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
(anonymous) @   view.js:664
(anonymous) @   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

1 回答

  • 1

    我使用0.9.0的angular2-websocket . 升级到0.9.1后,一切都按预期工作 . 希望这些信息可以帮助其他人:不要使用v0.9.0 .

相关问题