Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

↖️ The missing Angular WebSocket module for connecting client applications to servers by@AngularClass

License

NotificationsYou must be signed in to change notification settings

PatrickJS/angular-websocket

Repository files navigation

Angular Websocket

Angular WebsocketJoin SlackJoin the chat at https://gitter.im/AngularClass/angular-websocketgdi2290/angular-websocket API Documentation

TravisBowernpmDependency StatusdevDependency StatusNPM

Status: Looking for feedback about new API changes

An AngularJS 1.x WebSocket service for connecting client applications to servers.

How do I add this to my project?

You can download angular-websocket by:

  • (prefered) Using bower and runningbower install angular-websocket --save
  • Using npm and runningnpm install angular-websocket --save
  • Downloading it manually by clickinghere to download development unminified version
  • CDN for developmenthttps://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.js
  • CDN for productionhttps://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.min.js

Usage

<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script><scriptsrc="bower_components/angular-websocket/angular-websocket.js"></script><sectionng-controller="SomeController"><ulng-repeat="data in MyData.collection track by $index"><li> {{ data }}</li></ul></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 connectionvardataStream=$websocket('ws://website.com/data');varcollection=[];dataStream.onMessage(function(message){collection.push(JSON.parse(message.data));});varmethods={collection:collection,get:function(){dataStream.send(JSON.stringify({action:'get'}));}};returnmethods;}).controller('SomeController',function($scope,MyData){$scope.MyData=MyData;});</script>

API

Factory:$websocket (in modulengWebSocket)

returns instance of $Websocket

Methods

nameargumentsdescription
$websocket
constructor
url:StringCreates and opens aWebSocket instance.
var ws = $websocket('ws://foo');
senddata:String,Object returnsAdds data to a queue, and attempts to send if socket is ready. Accepts string or object, and will stringify objects before sending to socket.
onMessagecallback:Function
options{filter:String,RegExp, autoApply:Boolean=true}
Register a callback to be fired on every message received from the websocket, or optionally just when the message'sdata property matches the filter provided in the options object. Each message handled will safely call$rootScope.$digest() unlessautoApply is set to `false in the options. Callback gets called with aMessageEvent object.
onOpencallback:FunctionFunction to be executed each time a socket connection is opened for this instance.
onClosecallback:FunctionFunction to be executed each time a socket connection is closed for this instance.
onErrorcallback:FunctionFunction to be executed each time a socket connection has an Error for this instance.
closeforce:Boolean:optionalClose the underlying socket, as long as no data is still being sent from the client. Optionally force close, even if data is still being sent, by passingtrue as theforce parameter. To check if data is being sent, read the value ofsocket.bufferedAmount.

Properties

nametypedescription
socketwindow.WebSocketWebSocket instance.
sendQueueArrayQueue ofsend calls to be made on socket when socket is able to receive data. List is populated by calls to thesend method, but this array can be spliced if data needs to be manually removed before it's been sent to a socket. Data is removed from the array after it's been sent to the socket.
onOpenCallbacksArrayList of callbacks to be executed when the socket is opened, initially or on re-connection after broken connection. Callbacks should be added to this list through theonOpen method.
onMessageCallbacksArrayList of callbacks to be executed when a message is received from the socket. Callbacks should be added via theonMessage method.
onErrorCallbacksArrayList of callbacks to be executed when an error is received from the socket. Callbacks should be added via theonError method.
onCloseCallbacksArrayList of callbacks to be executed when the socket is closed. Callbacks should be added via theonClose method.
readyStateNumber:readonlyReturns either the readyState value from the underlying WebSocket instance, or a proprietary value representing the internal state of the lib, e.g. if the lib is in a state of re-connecting.
initialTimeoutNumberThe initial timeout, should be set at the outer limits of expected response time for the service. For example, if your service responds in 1ms on average but in 10ms for 99% of requests, then set to 10ms.
maxTimeoutNumberShould be as low as possible to keep your customers happy, but high enough that the system can definitely handle requests from all clients at that sustained rate.

CancelablePromise

This type is returned from thesend() instance method of $websocket, inherits from$q.defer().promise.

Methods

nameargumentsdescription
cancelAlias todeferred.reject(), allows preventing an unsent message from being sent to socket for any arbitrary reason.
thenresolve:Function, reject:FunctionResolves when message has been passed to socket, presuming the socket has areadyState of 1. Rejects if the socket is hopelessly disconnected now or in the future (i.e. the library is no longer attempting to reconnect). All messages are immediately rejected when the library has determined that re-establishing a connection is unlikely.

Service:$websocketBackend (in modulengWebSocketMock)

Similar tohttpBackend mock inAngularJS'sngMock module. You can usengWebSocketMock to mock a websocketserver in order to test your applications:

var$websocketBackend;beforeEach(angular.mock.module('ngWebSocket','ngWebSocketMock');beforeEach(inject(function(_$websocketBackend_){$websocketBackend=_$websocketBackend_;$websocketBackend.mock();$websocketBackend.expectConnect('ws://localhost:8080/api');$websocketBackend.expectSend({data:JSON.stringify({test:true})});}));

Methods

nameargumentsdescription
flushExecutes all pending requests
expectConnecturl:StringSpecify the url of an expected WebSocket connection
expectCloseExpect "close" to be called on the WebSocket
expectSendmsg:StringExpectation of send to be called, with required message
verifyNoOutstandingExpectationMakes sure all expectations have been satisfied, should be called in afterEach
verifyNoOutstandingRequestMakes sure no requests are pending, should be called in afterEach

Frequently asked questions

  • Q.: What if the browser doesn't support WebSockets?
  • A.: This module will not help; it does not have a fallback story for browsers that do not support WebSockets. Please check your browser target supporthere and to include fallback support.

Development

$ npm install$ bower install

Changelog

Changelog

Unit Tests

$ npm test Run karma in Chrome, Firefox, and Safari

Manual Tests

In the project root directory openindex.html in the example folder or browserify example

Distribute

$ npm run dist Builds files with uglifyjs

Support, Questions, or Feedback

Contact us anytime for anything about this repo or Angular 2

TODO

  • Allow JSON if object is sent
  • Allow more control over $digest cycle per WebSocket instance
  • Add Angular interceptors
  • Add .on(event)
  • Include more examples of patterns for realtime Angular apps
  • Allow for optional configuration object in $websocket constructor
  • Add W3C Websocket support
  • Add socket.io support
  • Add SockJS support
  • Add Faye support
  • Add PubNub support

enjoy —AngularClass



AngularClass##AngularClass

Learn AngularJS, Angular 2, and Modern Web Development form the best.Looking for corporate Angular training, want to host us, or Angular consulting?patrick@angularclass.com

License

MIT

About

↖️ The missing Angular WebSocket module for connecting client applications to servers by@AngularClass

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors23


[8]ページ先頭

©2009-2025 Movatter.jp