AngularJS socket, angularjssocket

Source: Internet
Author: User

AngularJS socket, angularjssocket

Load the Service-layer socket in the project Controller file. js. when you enter the page where the controller is located, connect to the socket (you can also connect to the project as soon as you enter it, depending on your needs). The details still need to be optimized. Write them down to prevent forgetting ~
Service layer: socket. js

/*************************************** **************************************** Angular Websocket Service *********************************** author: rigoal *************************************** * ******** created: 2014-04-01 ***************************/angular. module ('webbucketservice', []). service ('swsocket ', [' $ timeout', function ($ timeout) {var self = this; var callbackPool = []; // onMessage classification processing function va R delayPool = []; // delay processing request var registerPool = []; // The registered method 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. onc Lose = function (evnt) {onclose (evnt)}; wsTmp. onerror = function (evnt) {onError (evnt)}; return wsTmp;} ws = newWebSocket (); function onOpen () {ws. readyState = true; updateStatus ("onOpen:" + (connected? 'Ttrruuee ': 'ffaalless'); // request in the cache pool 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) {// handle the received data here var evenData = JSON. parse (evnt. data); console. log ("Received data from websocket:", evenData); // return processing // if (evenData. appId = 'register ') // {// if (evenData. methodId = 'unregister ') {// method return success, add method pool // if (evenData. content. status = 'succee D') {// registerPool. push ({appId: evenData. content. appId, methodId: evenData. content. methodId}); // console. log ("registerPool:", registerPool); //} else {// method return failure, resend the request //} // execute the callback function // return the data pushed in real time by the backend. <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) ;}// registration method // after successful registration, the system constantly listens to the data of the corresponding part pushed by the backend until the method self is deregistered. register = function (appId, methodId, callbackFuns) {var webSocketRe ={}; webSocketRe. appId = 'register '; webSocketRe. metho DId = 'register '; webSocketRe. content = {appId: appId, methodId: methodId}; if (ws. readyState! = True) {// websocket service does not open 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 ("callback Pool: ", callbackPool); return doSend (webSocketRe) ;}/// logout method // notifies the backend that the corresponding data is no longer pushed to self. unregister = function (appId, methodId, callbackFuns) {console. log ("unregister"); var webSocketRe ={}; webSocketRe. appId = 'register '; webSocketRe. methodId = 'unregister '; webSocketRe. content = {appId: appId, methodId: methodId}; // 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; // check the callback pool angular cyclically. 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); // This method does not exist in the callback function pool before the websocket request is actually sent. // the backend will no longer push the corresponding data if (num = 0) {doSend (webSocketRe) ;}}// actually sends the websocket request 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; // you do not need to register 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 layer:
<Pre name = "code" class = "javascript"> /************************** **************************************** * ************ Angular Websocket Controller ************************ * ********* author: rigoal *************************************** * ******** 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 = 'logon successful '; console. log ("doLogin"); $ location. path ('/home'); var content2 = {userName: 'hmm', userPassword: '000000'}; // websocket login to sWSocket. send ('login', 'login', content2); // consider extreme situations, A page has multiple modules listening to the same method // but the data displayed on the page needs to be processed differently for the received real-time listening data // The registration method heartBeat after login, the callback function callback // cancels this method sWSocket only when the page is switched (that is, when the scope is logged out. register (appId, methodId, callback); // The heartBeat method is also registered after login. The callback function callback1 // 3 s will immediately log off this method 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', "operation failed", success. resultReason); $ scope. status = success. resultReason ;};}). error (function (error) {$ scope. status = 'logon failed: '+ error. message;}) ;}; $ scope. logout = function () {loginFactory. logout (). success (function () {$ scope. status = 'exited successfully'; console. log ("logout ");}). error (function (error) {$ scope. status = 'exit failed: '+ error. message;}) ;}; // method heartBeat used to log out when logging out of scope. The callback function callback $ scope. $ on ("$ destroy", function () {console. log ("on-destroy"); sWSocket. unregister (appId, methodId, callback );});});





Php Runtime Environment

We recommend a software Xampp for you.
Just like installing windows, after installation, your computer becomes a PHP + MySQL + FTP server without any configuration. It's a Dummies. Just search online.

PHP websites are not difficult to use.

I think PHP is good.
You need to first check what is going on in html?
Then we know the process of C.
Then you will naturally know about PHP!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.