代码之家  ›  专栏  ›  技术社区  ›  joshrathke

如何在Angular 2/4+和Socket.io中关闭websocket

  •  2
  • joshrathke  · 技术社区  · 9 年前

    我试图创建一个使用websocket的应用程序,但遇到了可怕的“多连接”问题,每次重新加载页面而不是关闭并重新打开一个新的websocket时,另一个连接就会简单地添加到列表中。我的问题是,是否有人知道关闭插座的最佳/正确方法。io websocket来自角度2/4+。

    服务.ts

    getUserSocket(userID: string): Observable<any> {
        return new Observable(_Observer => {
    
            // Setup the socket namespace subscription
            this.UserSocket = io(NTC_API_URL + `/user/${userID}`, { secure: true });
    
            this.UserSocket.on('message', _Message => {
                console.log(_Message);
            })
        })
    }
    
    closeUserSocket() {
        this.UserSocket.disconnect();
        this.UserSocket.close();
    }
    

    组件.ts

    ngOninit() {
        // Setup the User Socket
        this.UserSocket = this._UsersService.getUserSocket(this.currentUser.userID)
        .subscribe(_UserSocketMessage => {
            console.log(_UserSocketMessage);
        })
    }
    
    ngOnDestroy() {
        this.UserSocket.unsubscribe();
        this._UsersService.closeUserSocket();
    }
    

    我尝试的另一个选择是使用 once on listener,这很管用,但我不确定副作用,我已经阅读了一些地方,这不一定是因为没有关闭连接的修复,我可以理解。

    1 回复  |  直到 9 年前
        1
  •  1
  •   joshrathke    9 年前

    经过相当多的修补和研究,我突然意识到web套接字是有弹性的。换句话说,由于它们被设计为在可能的情况下重新连接,因此专注于 disconnect 和 close 创造 web套接字连接数。

    从角度来看,这也很简单,因为我所要做的就是将套接字分配给服务中的一个属性,然后在进行套接字连接之前检查它是否存在。因此,只有在以前不存在连接的情况下才创建连接。

    // Setup the socket namespace subscription
    if (!this.UserSocket) {
        // Initialize user permissions socket
        this.UserSocket = io(NTC_API_URL + `/user/${this.LocalUser.userID}`, { secure: true });
    }
    
    推荐文章