Skip to content

Instantly share code, notes, and snippets.

@r10r
Forked from dpwiz/controllers.js
Created July 25, 2014 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r10r/b118465d0a7ca83a5711 to your computer and use it in GitHub Desktop.
Save r10r/b118465d0a7ca83a5711 to your computer and use it in GitHub Desktop.
function WSTestCtrl($scope, ws) {
$scope.method = 'ping'
$scope.params = '[]'
$scope.reply = 'None yet.'
$scope.reply_class = 'info'
$scope.go = function(){
ws.call($scope.method, JSON.parse($scope.params)).then(function(d){
$scope.reply = JSON.stringify(d)
$scope.reply_class = 'success'
}, function(e){
$scope.reply = JSON.stringify(e)
$scope.reply_class = 'danger'
})
}
}
werfns.factory('ws', ['$q', '$location', '$rootScope', function($q, $location, $rootScope) {
var callbacks = {}
var current_cb_id = 0
var ready = false
if ($location.protocol() == 'https') {
url = 'wss://' + window.location.hostname + '/ws'
} else {
url = 'ws://' + window.location.hostname + ':10000'
}
var ws = new WebSocket(url)
ws.onopen = function(){
console.debug("WS ready")
ready = true
}
ws.onmessage = function(msg) {
var reply = JSON.parse(msg.data)
console.debug("Received data from websocket: ", reply)
if (!!reply['id']) {
if(!!reply['error']) {
console.debug("Firing callback with error", reply['error'])
$rootScope.$apply(callbacks[reply.id].cb.reject(reply.error))
}
if(!!reply['result']) {
console.debug("Firing callback with result", reply['result'])
$rootScope.$apply(callbacks[reply.id].cb.resolve(reply.result))
}
delete callbacks[reply.id]
} else {
console.error('Got a reply without ID:', reply)
}
}
return {
call: function(method, params) {
var request = {
"jsonrpc": "2.0",
"method": method,
"params": params
}
current_cb_id += 1
request.id = current_cb_id
var defer = $q.defer()
callbacks[request.id] = {
time: new Date(),
cb: defer
}
console.debug("Sending request", request, ready)
if (!ready) { console.error('WS not ready!'); }
ws.send(JSON.stringify(request))
return defer.promise
},
notify: function(method, params) {
}
}
}])
<h3>WebSocket Test</h3>
<div class="row">
<div class="col-lg-5 panel panel-info">
<div class="panel-heading">Request</div>
<p><input type="text" ng-model="method" placeholder="method"/></p>
<p><textarea cols="40" rows="10" ng-model="params"></textarea></p>
</div>
<div class="col-lg-2" align="center">
<button class="btn btn-large btn-primary" ng-click="go()">Go!</button>
</div>
<div class="col-lg-5 panel" ng-class="'panel-' + reply_class">
<div class="panel-heading">Reply</div>
{{ reply }}
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment