我想在客户端使用web-socket进行服务器通信。 \
我正在使用AngularJS。我不想使用HTML5网络套接字。请帮我解释如何在AngularJS中实现web-socket
答案 0 :(得分:0)
angular-websocket:
由于这是一次性活动,如果应用程序库中的angular-websocket可用,请不要再次安装。如果不可用,请选择以下任一选项进行安装。
(首选)使用凉亭和运行凉亭安装angular-websocket --save 使用npm并运行npm install angular-websocket --save 通过单击此处下载开发未经授权的版本手动下载 CDN for development https://rawgit.com/gdi2290/angular-websocket/v1.0.9/angular-websocket.js CDN for production https://cdn.rawgit.com/gdi2290/angular-websocket/v1.0.9/angular-websocket.min.js
用法:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="bower_components/angular-websocket/angular-websocket.js"></script>
<section ng-controller="SomeController">
<ul>
<li ng-repeat="data in MyData.collection track by $index">
{{ data }}
</li>
</ul>`enter code here`
</section>
<script>
angular.module('YOUR_APP', [
'ngWebSocket' // you may also use 'angular-websocket' if you prefer
])
// WebSocket works as well
.factory('MyData', function($websocket) {
// Open a WebSocket connection
var dataStream = $websocket('wss://website.com/data');
var collection = [];
dataStream.onMessage(function(message) {
collection.push(JSON.parse(message.data));
});
var methods = {
collection: collection,
get: function() {
dataStream.send(JSON.stringify({ action: 'get' }));
}
};
return methods;
})
.controller('SomeController', function ($scope, MyData) {
$scope.MyData = MyData;
});
</script>
参考: