angular的websocket使用
<
script
src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></
script
>
<
script
src="//cdn.bootcss.com/angular-websocket/2.0.1/angular-websocket.js"></
script
>
第一种写法:后端向前端发送数据(直接响应onmessage)
/** * websocket */ app.factory('myWebsocket', function ($websocket, $timeout, $rootScope, storage, $http) { // Open a WebSocket connection function mywebscoket(){ this.mywebsocket = null; this.collection = {}; this.uijobstatuses = {}; var self = this; //打开websocket this.openWebSocket = function(userid){ var dataStream = $websocket('ws://localhost:8080/websocket?' + userid); dataStream.socket.onopen = function (evnt) { console.log("Webscoket opened."); }; dataStream.socket.onmessage = function (evnt) { self.onMessage(evnt) /*if(!$rootScope.$$phase) { // prevents triggering a $digest if there's already one in progress $rootScope.$digest() }*/ //$timeout(angular.noop); }; //关闭webscoket,比如后端服务器关闭了之后,直接会进入这个代码,然后在前端可以直接删除用户信息的token dataStream.socket.onclose = function (evnt) { debugger; storage.remove('loginname'); storage.remove('token'); $http.defaults.headers.common["Authorization"] = undefined; console.log("Webscoket closed."); }; dataStream.socket.onerror = function (evnt) { console.log("Webscoket Error."); }; this.mywebsocket = dataStream; } this.closeWebSocket = function(){ if(this.mywebsocket != null){ this.mywebsocket.close(); } } //后端向前端发送数据,前端接收 this.onMessage = function(message) { var data = JSON.parse(message.data); var modelName = data.modelname; var realObj = data.data; var colData = this.collection[modelName]; var colChild = {}; var uijobstatus = {"id":"","eto":"","subject":"","message":"","percentcomplete":"","status":0,"statusRetention":""}; if(colData == undefined || colData == null){ if(modelName == 'JobTaskVO'){ var jobStatuses = this.collection['JobStatusVO']; if(jobStatuses != undefined && jobStatuses != null){ var jobstatus = jobStatuses[realObj.jobid]; uiJobStatus = this.uijobstatuses[realObj.jobid]; if(jobstatus == undefined || jobstatus == null){ console.log('Can not find the JobStatusVO in collection,can not store the JobTaskVO'); console.log(realObj); }else{ if(jobstatus.jobtasks == undefined || jobstatus.jobtasks == null){ obstatus.jobtasks = []; } jobstatus.jobtasks.push(realObj); if(uiJobStatus != undefined && uiJobStatus != null){ uiJobStatus.status = realObj.status; uiJobStatus.message = realObj.message; uiJobStatus.percentcomplete = realObj.percentcomplete; } } }else{ console.log("Can not find any JobStatusVO in collection"); } }else{ if(modelName == 'JobStatusVO'){ uijobstatus.id = realObj.id; uijobstatus.eto = realObj.eto; uijobstatus.subject = realObj.subject; uijobstatus.statusRetention = realObj.statusRetention; this.uijobstatuses[realObj.id] = uijobstatus; } colChild[realObj.id] = realObj; this.collection[modelName] = colChild; } }else{ if(modelName == 'JobStatusVO'){ uijobstatus.id = realObj.id; uijobstatus.eto = realObj.eto; uijobstatus.subject = realObj.subject; uijobstatus.statusRetention = realObj.statusRetention; this.uijobstatuses[realObj.id] = uijobstatus; } colData[realObj.id] = realObj; } }; } return new mywebscoket(); });
第二种方式:(向服务器发送信息)
angular.module('chatApp') .factory('myWebsocket', function ($websocket) { // Open a WebSocket connection var dataStream = $websocket('ws://localhost:8888/chatsocket'); var contents = []; dataStream.socket.onopen = function (evnt) { console.log("Webscoket opened."); }; dataStream.socket.onmessage = function (evnt) { onmessage(evnt.data); } dataStream.socket.onclose = function (evnt) { console.log("Webscoket closed."); }; dataStream.socket.onerror = function (evnt) { console.log("Webscoket Error."); }; jQuery.fn.formToDict = function () { var fields = this.serializeArray(); var json = {} for (var i = 0; i < fields.length; i++) { json[fields[i].name] = fields[i].value; } if (json.next) delete json.next; return json; }; var onmessage = function (evnt) { contents.push(JSON.parse(evnt)); } var methods = { contents: contents, get: function (form) { //form表示表单form的id var message = form.formToDict(); contents.push(message); dataStream.socket.send(JSON.stringify(message)); } }; return methods; });
html:
<form id="messageform"> <input type="text" autocomplete="off" ng-model="chat.sendContent" name="text" id="serializeInfo" value="" placeholder="输入你的消息..." maxlength="500" ng-keyup="keyupMessage($event)"> <input type="text" name="eid" id="eid" style="display:none" /> <input type="text" name="type" value="0" style="display:none" /> <input type="text" name="uuid" id="uuid" style="display:none" /> <button type="button" class="enterIcon" ng-click="sendMessage($event)"> <img src="images/Group 137.png"> </button> </form>
//主要用于对话实时刷新数据,且滚动条跟着动
angular.module('chatApp') .controller('MainCtrl', function ($scope, internetService, myWebsocket, $interval) { $scope.chat = { content: [], sendContent: $scope.inputdata } //chat //显示消息 $scope.sendMessage = function (event) { myWebsocket.get($('#messageform')); $scope.chat.content = myWebsocket.contents; $scope.chat.sendContent = ""; $('#serializeInfo').focus(); $('#divbot').scrollTop($('#divbot')[0].scrollHeight); console.log($scope.chat.content); } $scope.keyupMessage = function (event) { if (event.keyCode == 13) { myWebsocket.get($('#messageform')); $scope.chat.content = myWebsocket.contents; $scope.chat.sendContent = ""; $('#serializeInfo').focus(); $('#divbot').scrollTop($('#divbot')[0].scrollHeight); return false; } } $scope.setinter = function () { var promise = $interval(function () { //if (myWebsocket.contents.length > 0) { //if (myWebsocket.contents.length > $scope.chat.content.length) { $scope.chat.content = myWebsocket.contents; $('#divbot').scrollTop($('#divbot')[0].scrollHeight); //} //} }, 1000); return promise; } var promise = $scope.setinter(); $scope.$on("$destroy", function () { $interval.cancel(promise); }); $scope.$watch('chat.content + chat.sendContent', function () { setTimeout(function () { $('#divbot').scrollTop($('#divbot')[0].scrollHeight); }, 0); }); });