angularJS socket
工程Controller加载文件Service层socket.js.controller所在页面时连接socket(也可一进入项目就连接,看需求)。细节还需继续优化,写下来以防忘了~
Service层:socket.js
/************************************************************* ******************Angular Websocket Service****************** ******************author:ristal****************************** ******************created:2014-04-01**************************/ angular.module('websocketService', []) .service('sWSocket', ['$timeout', function ($timeout) { var self = this; var callbackPool = []; //onMessage分类处理函数 var delayPool = []; //延迟处理请求 var registerPool = [];//已注冊的方法 var data = {}; var ws = null; var connected = false; function newWebSocket() { // var wsURL = "ws://10.188.199.4:8080/YIXUN_1.5_WEB/websocket/"; var wsURL = "ws://10.188.192.200:8000/websocket/"; var wsTmp = new WebSocket(wsURL); wsTmp.onopen = function (evnt) { onOpen(evnt) }; wsTmp.onmessage = function (evnt) { onMessage(evnt) }; wsTmp.onclose = function (evnt) { onclose(evnt) }; wsTmp.onerror = function (evnt) { onError(evnt) }; return wsTmp; } ws = newWebSocket(); function onOpen() { ws.readyState = true; updateStatus("onOpen : " + (connected ?'TTRRUUEE' : 'FFAALLESS')); //缓存池中存在请求 while (delayPool.length > 0) { var popData = delayPool.shift(); if (popData.isReg == 1) { self.register(popData.appId, popData.methodId, popData.scope, popData.callbackFuns); } else if(popData.isReg == 0){ self.unRegister(popData.appId, popData.methodId, popData.scope, popData.callbackFuns); }else { self.send(popData.appId, popData.methodId, popData.content); } } } function onclose() { ws.readyState = false; updateStatus("onClosed : " + (connected ? 'TTRRUUEE' : 'FFAALLESS')); $timeout(function () { console.log('Reconnecting to server...') newWebSocket(); }, 3000); } function onMessage(evnt) { //这里处理接收数据 var evenData = JSON.parse(evnt.data); console.log("Received data from websocket: ", evenData); // //返回处理 // if(evenData.appId === 'register') // { // if(evenData.methodId === 'unRegister'){ // //方法返回成功,增加方法池 // if(evenData.content.status == 'SUCCEED'){ // //registerPool.push({appId: evenData.content.appId, methodId: evenData.content.methodId}); // console.log("registerPool:", registerPool); // }else{//方法返回失败,又一次发送请求 // // } // } // } //运行回调函数 //传回后端实时推送的数据 <span style="color:#ff0000;"> angular.forEach(callbackPool,function(value){ if(value.appId === evenData.appId && value.methodId === evenData.methodId){ value.callback(evenData.content); } });</span> } function onError(evnt) { ws.readyState = false; console.log('ERROR: ', evnt); $timeout(function () { console.log('Reconnecting to server...') newWebSocket(); }, 3000); } function updateStatus(status) { console.log(status); } //注冊方法 //注冊成功后会一直监听后端推送的对应部分的数据 //直到注销此方法 self.register = function (appId, methodId, callbackFuns) { var webSocketRe = {}; webSocketRe.appId = 'register'; webSocketRe.methodId = 'register'; webSocketRe.content = { appId: appId, methodId: methodId }; if (ws.readyState != true){//websocket服务未打开 webSocketRe.isReg = 1;//register webSocketRe.appId = appId; webSocketRe.methodId = methodId; webSocketRe.callbackFuns = callbackFuns; delayPool.push(webSocketRe); console.log("register-delayPool:", delayPool); console.log("sending is delay."); return "sending is delay."; } else { callbackPool.push({appId:appId,methodId:methodId,callback:callbackFuns}); console.log("callbackPool:",callbackPool); return doSend(webSocketRe); } } //注销方法 //通知后端不再推送对应数据 self.unregister = function (appId, methodId,callbackFuns) { console.log("unregister"); var webSocketRe = {}; webSocketRe.appId = 'register'; webSocketRe.methodId = 'unRegister'; webSocketRe.content = { appId: appId, methodId: methodId }; //websocket服务未开启 if (ws.readyState != true){ webSocketVo.isReg = 0;//unRegister delayPool.push(webSocketRe);// console.log("unregister is delay."); return "unregister is delay."; } else { console.log("sending unregister."); var num = 0; //循环检查回调函数池 angular.forEach(callbackPool,function(value,key){ if(value.appId === appId && value.methodId === methodId){ num += 1; if(value.callback === callbackFuns){ delete callbackPool[key]; num -=1; } } }); console.log("num:",num); console.log("callbackpool:",callbackPool); //回调函数池中已经不存在此方法才真正发送websocket请求 //通知后端不再推送对应数据 if(num === 0 ){ doSend(webSocketRe); } } } //实际发送websocket请求 function doSend(webSocketVo) { return ws.send(JSON.stringify(webSocketVo)); } self.send = function (appId, methodId, content) { var webSocketVo = {}; webSocketVo.appId = appId; webSocketVo.methodId = methodId; webSocketVo.content = content; if (ws.readyState == 0) { // webSocketVo.isReg = false;//不须要注冊 delayPool.push(webSocketVo); console.log("sending is delay."); return "sending is delay."; } else { console.log("sending is doing."); console.log("webSocketVo:",webSocketVo); return doSend(webSocketVo); } } return self; }]);
Controller层:
<pre name="code" class="javascript">/************************************************************* ******************Angular Websocket Controller**************** ******************author:ristal****************************** ******************created:2014-04-01**************************/ angular.module('websocketControllers') .controller('loginCtrl', function ($scope,loginFactory,sWSocket,toaster,$location,$timeout) { console.log("loginCtrl"); $scope.status; var appId = 'heartBeat'; var methodId = 'heartBeat'; var callback = function(evendata){ console.log("callback:",evendata); $scope.menu = evendata; $scope.$apply(); console.log($scope.menu); } var callback1 = function(evendata){ console.log("callback1:",evendata); $scope.menu = evendata; $scope.$apply(); console.log($scope.menu); } $scope.doLogin = function(user){ loginFactory.doLogin(user) .success(function (success) { if(success.resultCode == 200){ $scope.status = '登录成功'; console.log("doLogin"); $location.path('/home'); var content2 = { userName:'hmm', userPassword:'111' }; //websocket登陆 sWSocket.send('login', 'doLogin', content2); //考虑极端情况。一个页面有多个模块监听同一个方法 //但展示在页面的数据需对接收的实时监听的数据做不同处理 //登陆后注冊方法heartBeat。回调函数callback //页面切换时(也就是注销scope时)才注销此方法 sWSocket.register(appId,methodId,callback); //登陆后也注冊方法heartBeat,回调函数callback1 //3s后马上注销此方法 sWSocket.register(appId,methodId, callback1); $timeout(function () { console.log("unregister callback1"); sWSocket.unregister(appId,methodId,callback1); }, 3000); }else if (success.resultCode == 102) { toaster.pop('error', "操作失败", success.resultReason); $scope.status = success.resultReason; }; }) .error(function (error) { $scope.status = '登录失败: ' + error.message; }); }; $scope.logout = function(){ loginFactory.logout() .success(function () { $scope.status = '退出成功'; console.log("logout"); }) .error(function (error) { $scope.status = '退出失败: ' + error.message; }); }; //注销scope时注销方法heartBeat。回调函数callback $scope.$on("$destroy",function(){ console.log("on-destroy"); sWSocket.unregister(appId,methodId,callback); }); });
版权声明:本文博客原创文章,博客,未经同意,不得转载。