GithubHelp home page GithubHelp logo

patrickjs / angular-websocket Goto Github PK

View Code? Open in Web Editor NEW
1.2K 60.0 194.0 6.02 MB

:arrow_upper_left: The missing Angular WebSocket module for connecting client applications to servers by @AngularClass

Home Page: https://angularclass.github.io/angular-websocket

License: MIT License

JavaScript 99.90% HTML 0.10%
angular angularclass websocket websockets angular2 angular4

angular-websocket's Introduction

Angular Websocket

Angular Websocket Join Slack Join the chat at https://gitter.im/AngularClass/angular-websocket gdi2290/angular-websocket API Documentation

Travis Bower npm Dependency Status devDependency Status NPM

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 running bower install angular-websocket --save
  • Using npm and running npm install angular-websocket --save
  • Downloading it manually by clicking here to download development unminified version
  • CDN for development https://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.js
  • CDN for production https://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.min.js

Usage

  <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 ng-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 connection
      var dataStream = $websocket('ws://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>

API

Factory: $websocket (in module ngWebSocket)

returns instance of $Websocket

Methods

name arguments description
$websocket
constructor
url:String Creates and opens a WebSocket instance.
var ws = $websocket('ws://foo');
send data:String,Object returns Adds data to a queue, and attempts to send if socket is ready. Accepts string or object, and will stringify objects before sending to socket.
onMessage callback: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's data property matches the filter provided in the options object. Each message handled will safely call $rootScope.$digest() unless autoApply is set to `false in the options. Callback gets called with a MessageEvent object.
onOpen callback:Function Function to be executed each time a socket connection is opened for this instance.
onClose callback:Function Function to be executed each time a socket connection is closed for this instance.
onError callback:Function Function to be executed each time a socket connection has an Error for this instance.
close force:Boolean:optional Close 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 passing true as the force parameter. To check if data is being sent, read the value of socket.bufferedAmount.

Properties

name type description
socket window.WebSocket WebSocket instance.
sendQueue Array Queue of send calls to be made on socket when socket is able to receive data. List is populated by calls to the send 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.
onOpenCallbacks Array List 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 the onOpen method.
onMessageCallbacks Array List of callbacks to be executed when a message is received from the socket. Callbacks should be added via the onMessage method.
onErrorCallbacks Array List of callbacks to be executed when an error is received from the socket. Callbacks should be added via the onError method.
onCloseCallbacks Array List of callbacks to be executed when the socket is closed. Callbacks should be added via the onClose method.
readyState Number:readonly Returns 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.
initialTimeout Number The 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.
maxTimeout Number Should 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 the send() instance method of $websocket, inherits from $q.defer().promise.

Methods

name arguments description
cancel Alias to deferred.reject(), allows preventing an unsent message from being sent to socket for any arbitrary reason.
then resolve:Function, reject:Function Resolves when message has been passed to socket, presuming the socket has a readyState 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 module ngWebSocketMock)

Similar to httpBackend mock in AngularJS's ngMock module. You can use ngWebSocketMock to mock a websocket server 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

name arguments description
flush Executes all pending requests
expectConnect url:String Specify the url of an expected WebSocket connection
expectClose Expect "close" to be called on the WebSocket
expectSend msg:String Expectation of send to be called, with required message
verifyNoOutstandingExpectation Makes sure all expectations have been satisfied, should be called in afterEach
verifyNoOutstandingRequest Makes 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 support here 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 open index.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? [email protected]

License

MIT

angular-websocket's People

Contributors

b264 avatar battmanz avatar bonifaido avatar davej avatar elecash avatar gitter-badger avatar gomezgoiri avatar head avatar jenselme avatar patrickjs avatar rahulshukla111 avatar raszpi avatar readmecritic avatar reymalahay avatar robertknight avatar spiroid avatar stegoo avatar vanishs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-websocket's Issues

onMessage not being called when server sends arbitrary data

Hi I am using this library for an iOS app. The problem I am facing is I can see the web socket being initialized and when I am running my app and I bring down the web socket server, I see my app trying to reconnect, so I know the socket is alive, but when the server is sending any message (I am sending "test" every 5 seconds from the server) my onMessage callback is never called. I know the server works because I am running a web socket client in Chrome as well and it receives it, but not my app.

Can someone tell me if they see something wrong in my app code:

angular.module('zmApp.controllers').service('EventServer', 
[  '$websocket', 'ZMDataModel', '$rootScope',function 
 (  $websocket, ZMDataModel, $rootScope) {

 ZMDataModel.zmLog("*************EVENT SERVER*************");
 var dataStream;

 var loginData = ZMDataModel.getLogin();

    ZMDataModel.zmLog ("webSocketStart: attempting to start a WSS connection");
    dataStream = $websocket( "wss://<server name removed>", {reconnectIfNotNormalClose: true});


        dataStream.onMessage(function(message) {
            ZMDataModel.zmLog("GOT WEBSOCKET MESSAGE:" + JSON.parse(message.data));
        });

        dataStream.onError(function(message) {
            ZMDataModel.zmLog("GOT WEBSOCKET ERROR:" + JSON.parse(message.data));
        });




}]);

bufferutil & utf-8-validate failed on windows

MSBUILD : error MSB3428: Could not load the Visual C++ component "VCBuild.exe".
To fix this, 1) install the .NET Framework 2.0 SDK, 2) install Microsoft Visua
l Studio 2005 or 3) add the location of the component to the system path if it
is installed elsewhere. [C:\project\photosharing\src\main\frontend\node_module
s\angular-websocket\node_modules\ws\node_modules\bufferutil\build\binding.sln]

onmessage

When investigating dropped messages, I saw that the readystatechange / XMLHttpRequestProgressEvent was getting passed in instead.

From the stack trace, it seems to be getting triggered after a $get() by angular. I'm using AngularJS v1.2.21.

Any idea what the cause might be, or how I can better isolate the cause? Thanks.

onClose not called?

Hi. I'm switching my angularjs app from socket.io to pure websockets and am using your angular-websocket service. With the old socket.io every time I would loose the internet connection (just turn off wifi), the onClose handler would be called. This is not the case here, it's never called.

Is this a limitation of websockets, or a bug with your implementation?

Does not try to reconnect when connection is killed by server

When the socket server is restarted, the client socket connection gets the onclose event with code 1006. Since this isn't in _reconnectableStatusCodes, it never tries to reconnect again. Is there are reason that only code 4000 is in that list? What do the codes mean? Shouldn't it simply always try to reconnect unless the client explicitly close the connection?

Create party. With not a numbers in phone number.

Description

User can't enter any letters in party phone field, button "+Add" will be inactive.

Steps to reproduce issue

User tries to enter not a numbers in phone input field.

Expected result

User can't enter not a numbers in phone input field.

Actual result

User CAN enter not a numbers in phone input field and SAVE a party.

Other information

Reported by: Maxim Ugnichenko

Test case number: TC419

Test run: https://valorsoftware.testlodge.com/projects/15734/runs/188438?tab=2&run_section_id=160081&executed_case_id=9151158#executed_case_9151158

Tell the onClose handler how many reconnects were tried

Currently when the connection is closed it tries to reconnect and on success calls this code:

$WebSocket.prototype._onOpenHandler = function _onOpenHandler(event) {
    this._reconnectAttempts = 0;
    this.notifyOpenCallbacks(event);
    this.fireQueue();
};

A couple of weird things. I thought that this._reconnectAttempts is a configuration option, where you can tell the library how often to try to reconnect (since you can pass it along as options.reconnectAttempts), but it turns out that it's a counter that controls the reconnect delay and stuff. Why would I want to pass this is as an option? Would a maxReconnectAttempts maybe make sense instead?

The second thing: should it maybe be reset after calling this.notifyOpenCallbacks(event) so that my onOpen handler knows if it's called because of an initial connection or a reconnect? Right now I don't know the difference between an onOpen and an onReconnect, so to speak (which would be a nice handler to support btw).

Build fails on node 4.x due to old ws dependency

The build currently fails on Node 4.x due to a dependency on an old version of bufferutil via the ws dependency.

Given that the ws library is a completely trivial wrapper when used in the browser, is this dependency really needed? As noted at websockets/ws#577 it adds a whole bunch of extras that the user will need to have in order to build angular-websocket via npm.

I'm going to submit a PR to update the ws dependency but can you see any good reasons not to just remove the dependency entirely?

Relative url

Hi, a question, how can I set the websocket path realtive and not absolut.

ws://api/v1.... does not work

Is it possible also the set wss or ws dynamically? It depends from where I came if I came over https or http.

thx

Cannot find module 'ws'

I am getting this error: Cannot find module 'ws' from '/home/some/path/myproject/node_modules/angular-websocket'

I think this is because I use http://browserify.org/ and angular-websocket has this code.

   // CommonJS
  if (typeof exports === 'object' && require) {
    try {
      ws = require('ws');
      Socket = (ws.Client || ws.client || ws);
    } catch(e) {}
  }

  // Browser
  Socket = Socket || $window.WebSocket || $window.MozWebSocket;

append a linefeed to the minified file

Without an empty new line, it seems concatenation with other dependencies will end up wrong, and uglify will complain and fail.

specifying separator: ';\n' to grunt-contrib-concat won't help either.

I was able to to avoid this overriding the main file in my bower.json, because the non-minified version doesn't have the sourcemap comment and won't mess with concatenation without that linefeed

  "overrides": {
    "angular-websocket": {
      "main": ["angular-websocket.js"],
      "dependencies": {}
    }
  },

socket.io support status ?

I get a "WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response" error (at v1.0.14/angular-websocket.js:362)

However, if I replace
var dataStream = $websocket('ws://localhost:3000');
with a plain old socket.io :
var socket = io.connect('ws://localhost:3000') .on('news', function (data) { console.log(data); });
it works just fine.

Is that because socket.io is not supported (as your TODO list tends to suggest) or am I missing something ?

Accessing the onError headers

Hello,

Thank you for developing this! It's very easy to use and intuitive.

I'm using this library along with https://github.com/theturtle32/WebSocket-Node/blob/d5398c862b3aa460f71f1c77ddd6138d4e722eaf/docs/WebSocketRequest.md. Under the 'reject' section, you'll see that if a connection is rejected, the rejection message is passed along as a 'X-Websocket-Reject-Reason' header. Does angular-websocket provide any ways to access this header?

I'm happy to modify angular-websocket (this is for a demo) if there's an obvious place to insert the code, if that enables me to access the header.

Thank you!
Robert

Inconsistent reconnect behavior on Safari vs Chrome

Hello,

I would like to point out an incoherent behavior with the reconnect functionality depending on the used browser.

The issue happen after instantiating the $webcoket([url], [options]).
This instruction will result in sending an HTTP GET request of the specified URL.
In our case, the back-end did not send a response at all. The request was pending during approximately 30 seconds; here is the incoherent behavior.

In Chrome, the request gets the status "200 OK" with an empty response after 30 seconds, whereas in Safari the request fail (no status, no response).
This will cause the service to reconnect every 30 seconds on the listed OS X and iOS environments bellow.

The issue happened on the following environment:

  • OS X 10.11.4, Safari 9.1 (11601.5.17.1)
  • iOS 9.3 & 9.4 on Safari

We fixed the issue by forcing an empty dumb response of the back-end.
This is not an urgent issue, nor a frequent scenario, but it would be nice if you could address it.

Regards,

github-failed-request-safari
github-success-request-chrome

How is the WebSocket closed and reopened?

This is more of a question than an issue.
On a normal http request, the websocket would be reinstantiated when the page loads. However in ng, when using a routeProvider, and angular-websocket, navigating away from the controller and then back leaves the websocket open throughout.
How would you recommend closing and reopening the socket when navigating through ng routes?

Questions

This is also more a request than a bug. ¿Could you add a bit of documentation on the following topics?:

  • How websocket event re-broadcasting works.
  • How to automatically reconnect when the websocket is closed.

Remove listener?

Hello!

It would be great if the onMessage() would return an ID that could be later used to REMOVE that listener.

I am currently using one global websocket that I attach to on every controller. After a routechange I need to remove the registered listeners, but there seems to be no good way to do that.

Websocket tries to reconnect even when `close()` is explicitly called.

Whenever I try to connect to a webserver that rejects the connection, (for instance, if the server returns a 500 status code) then calling close() on the websocket does not stop it from trying to reconnect to the server. It only stops if the connection was successful and then close() is called.

Send messages from mock backend to client

The front-end application I am developing currently only consumes messages sent from the server. I would like to be able to test that I am handling the responses properly, and need to send a message from the mock backend to the client. Is this possible?

Thanks!

Error code of failed handshake

Hey, thanks for the great module.

Is there any way to get response codes or even full response when WS handshake fails?
At the moment, I'm using websocket with authentication using tickets, and when something is wrong, im sending back http codes 404, 403, or some other. On the client-side I have to show user the reason, that depends on response code.

Thanks in advance.

Feature request: ready promise

This is something easy enough to implement using the onOpen callback, but it would be nice to have a promise which resolves when the connection is open. If the websocket is opened in one service, and another service wants to use it, a promise seems like the most practical way to communicate when it is open.

Inside onClose callback scope changes never are applied

This code doesn't work:

ws.onClose(function (e) {
 $scope.anyVariable = anyValue;
}

I mean, scope variables are changed but not binding to the view. Binding is off

I fixed it using $scope.$digest(), but why not update?

'.' is not recognized as an internal or external command,

Hi there,

i am getting below error, could you pls let me know anything is missing here?

D:\angular-websocket-master>npm test

[email protected] test D:\angular-websocket-master
./test.sh

'.' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! Test failed. See above for more details.

Webpack throws warning

The usage of require throws this warning:
WARNING in .//angular-websocket/angular-websocket.min.js
Critical dependencies:
1:5077-5084 require function is used in a way in which dependencies cannot be statically extracted
@ ./
/angular-websocket/angular-websocket.min.js 1:5077-5084

(and a lot of other ones)

in the source file:
line 348: if (typeof exports === 'object' && require) {

basically webpack expects require to have parameters and without it, it tries to include all files in the directory.

URL is not valid

Why it gives me invalid url ?

I tried this :

var dataStream = $websocket('ws:://localhost:3000/api/students/testing');

and this :

var dataStream = $websocket('ws:://api/students/testing');

but it is no use

Send data / process request using $websocketBackend

Isn't the $websocketBackend supposed to act like httpbeckend mock, and send data / process messages? If not, how can I achieve this behaviour? So far I've found only nodeJS mock servers, not angular ones

Thank you in advance

Error in Firefox

What does this error mean?
error { target: WebSocket, isTrusted: true, currentTarget: WebSocket, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, timeStamp: 1439998565873491, originalTarget: WebSocket, explicitOriginalTarget: WebSocket, NONE: 0 }.

How to replicate:
1.) Use Firefox.
2.) Create a WebSocket connection.
3.) Click any <a> tag. e.g. <a href='file.txt' download>Download</a>.
4.) Use any feature that receives a message from the server using a WebSocket. (i.e. Send a message from server to client.)
5.) The error is received.
6.) WebSocket connection closes by itself.

Uncaught SyntaxError: Unexpected token h

I got error 'Uncaught SyntaxError: Unexpected token h' when executing usage first usage example. It points to anonymous function collection.push(JSON.parse(message.data)) ?

i got this when sending simple msg

"WebSocket connection to 'ws://localhost:9999/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received"

on server side it doesn't pass to handling message part, ends on create connetion part (tested with tornado 4.0.2)

src:
var ws = $websocket('ws://localhost:9999/');
ws.send(JSON.stringify({event:'pong',data:{}}));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.