angular集成websocket_AngularJS:重新连接服务中的WebSocket

在AngularJS应用中使用WebSocket,当用户登出时关闭连接。需要在用户重新登录时重新连接WebSocket。WebSocket在服务中实现,问题在于重新创建的WebSocket实例不工作。解决方案是在服务中创建新的WebSocket对象并手动附加事件处理器。
摘要由CSDN通过智能技术生成

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;

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?

解决方案

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;

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值