AngularJS:重新连接服务中的WebSocket [英] AngularJS: Reconnect WebSocket inside a service

查看:4044
本文介绍了AngularJS:重新连接服务中的WebSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯使用网络插座,我AngularJS应用。

当用户退出网络套接字连接是由客户端关闭。
我需要在用户登录后重新连接网络接口。

网络插座包含在服务中(code被简化了一下):

Im using web sockets in my AngularJS application.
When a user logs out the web socket connection is closed by the client. I need to reconnect the web socket when the user logs back on.
The web socket is contained within a service (code is simplified a bit):

angular.module('myApp').factory("SubscriptionFactory", function () {
    var Service = {};
    var ws = new WebSocket("ws://127.0.0.1:8000");

    /* WS methods (onopen, onmessage ect) left out for simplicity */

    Service.reestablishConnection = function() {
        // Reestablishing connection
        ws = new WebSocket("ws://127.0.0.1:8000");
    }
    return Service;

的问题是,在网络套接字的新实例不起作用。

据<一个href=\"http://stackoverflow.com/questions/13797262/how-to-reconnect-to-websocket-after-close-connection\">this 网络插座问题需要重新连接其处理对象的重建时。

但AngularJS服务是一个单独的(并应按照这个问题) 。

我怎样才能重建我的AngularJS单服务中的网络Socket实例?

The problem is that the new instance of the web socket does not work.
According to this question the web socket needs to reattach its handlers to the object when its recreated.
But a AngularJS service is a singleton (and should stay a singleton according to this question).
How can I recreate the web socket instance inside my AngularJS singleton service?

推荐答案

我找到了自己的解决方案。它实际上是pretty简单:

I found the solution myself. It was actually pretty simple:

angular.module('myApp').factory("SubscriptionFactory", function () {
    var Service = {};
    var ws;

    Service.onMessage = function(message) { /* some code */};
    Service.onClose = function() { /* some code */ };
    Service.onOpen = function() { /* some code */};
    Service.onError = function(error) { /* some code */};

    Service.connect = function() {
        // (Re)connect
        ws = new WebSocket("ws://127.0.0.1:8000");
        // Reattaching handlers to object
        ws.onmessage = Service.onMessage;
        ws.onclose = Service.onClose;
        ws.onopen = Service.onOpen;
        ws.onerror = Service.onError;
    }
    return Service;

这里发生的方法很简单:林创建新的Web Socket对象,并手动将网络套接字句柄连接到我的AngularJS服务

What happens here is simple: Im creating a new Web Socket object and manually attaching the Web Sockets handlers to my AngularJS service.

这篇关于AngularJS:重新连接服务中的WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆