AngularJS HTML5 WebSocket powerful library
0 people use it
Author: 647020?v=2 wilk


AngularJS HTML5 WebSocket powerful wrapper module to develop with ease and fun!



ngWebsocket is a library that provides a provider and a service to handle HTML5 WebSocket with ease in pure AngularJS style! The idea behind this module is to give four kinds of object to handle websockets:

  • $websocketProvider: the provider is on top of usage. In fact, you can setup a general configuration for each ngWebsocket you're going to create
  • $websocket: following an Angular service that lets you to handle different websocket instance among your application
  • ngWebsocket: an instance of the HTML5 WebSocket wrapper (this is actually the core of this module): it provides lots of feature to work with websockets
  • $$mockWebsocket: this is a smart implementation of a websocket backend that lets you to developer and test your app without a real responding server

For each of these objects an API is available and fully documented in this document.


The only requirement needed is AngularJS that you can install it via Bower.


Use Bower to install this module:

Or simply git clone the repo and install the dependencies with NPM:


After the Installation, require it in your Angular application.

Firstly, in your index.html:

Then, in your Angular application definition (assumed app.js):

Now, you're ready to use it!


Need to use HTML5 WebSocket to build your cool web application, huh? No problem, dude! Check this out!

Easy, right?

Well, let's chain it!

Your back-end team is lazy? No problem: we can do it on our own!


ngWebsocket comes from Italy with lots of interesting stuff, folks! Why not just a wrapper? Because we can do more with happiness and fun!

So, let's discover the awesome features list!


Using basic HTML5 WebSocket object, you experienced that the connection is open immediately, just after the websocket is created with new constructor. By default, the same behaviour is used by ngWebsocket but you can simply change it with this powerful feature:

With $websocket.$open function, you can open the connection when you want, especially after the coffee break.

Default: disabled


Ok, your websocket connection went down due to a bad wifi connection and you don't want to make another connection manually, right? So, what about an automated feature that do this for you?

With this feature, if the connection goes down, it will open again after 2 seconds by default. If you need to get the connection back in fewer time, just use the reconnectInterval time slice:

Pay attention, good sir: if you close the ngWebsocket with the $close method, it won't get the connection back until the $open is invoked!

Default: enabled


From great powers come great responsability. Keep this in mind while reading this feature.

Sometimes, it would be useful if someone save our websocket communication, especially when the connection is down. With this powerful feature, it's possible to store every unsent message in a queue and then flush them just the connection get up again.

How? Enabling enqueue feature, of course!

BUT this means that each message is stored into a memory queue and it can get really big, especially if your application sends many messages in a short time slice.

Default: disabled


Dulcis in fundo, a websocket server implementation to use and test your application, without a real websocket server listening! Yep, you well heard!

Think about this situation: you're developing the front-end part of your company application and the backend team is lazy (because every developer is lazy), so you couldn't start writing your section because you need to send/retrieve data to/from the server.

No problem, you can!

By default, the mock feature simulate a parrot websocket server: this means that every message sent with a certain event, will have a response with the same structure, with the same event and the same data.

However, you can setup some fixtures that simulate what your lazy back-end team is going to do after beer time:

Default: disabled


This module uses Karma with Jasmine for unit testing, so before launching any test check out if all dependencies are correctly installed:

After that, launch the test:


ngWebsocket APIs are composed by four different modules:

  • $websocketProvider
  • $websocket
  • ngWebsocket
  • $$mockWebsocket (private but configurable)


Following the API of ngWebsocket Provider


If you need to setup your custom default configuration for each ngWebsocket istance, pass it to this method:



| Param | Type | Details | | --------- | -------- | ----------- | | config | Object | default ngWebsocket configuration |


| Type | Details | | -------- | ----------- | | $websocketProvider | the $websocketProvider |


Following the API of the $websocket Service


Every ngWebsocket instance created with $websocket.$new method are stored within the $websocket service. To get one of them, you can use $get with the url of the websocket you're looking for:

The url is needed because it is stored using the url as the key of an hashmap.



| Param | Type | Details | | --------- | -------- | ----------- | | url | String | the websocket url |


| Type | Details | | -------- | ----------- | | ngWebsocket | an instance of ngWebsocket or undefined |


There are two ways to create a new instance of ngWebsocket:

string (url)

The url is always needed and it has to start with the websocket schema (ws:// or wss://):

A new instance is returned and the internal WebSocket has already started the connection with the websocket server on the backend.


All of the following configurations can be changed:

For more information see the ngWebsocket Constructor section.



| Param | Type | Details | | --------- | -------- | ----------- | | url/config | String/Object | websocket url or a configuration set |


| Type | Details | | -------- | ----------- | | ngWebsocket | an instance of ngWebsocket |


ngWebsocket is the core of this module. In a few words, it's a wrapper for the HTML5 WebSocket object, extending it with different features. It acts like an EventEmitter and it provides a common way to attach a handler for each fired event.

Following the API in detail.


The constructor of the ngWebsocket accepts two kind of parameters:

  • String: the url starting with the WebSocket schema (ws:// or wss://)
  • Object: a configuration containing the websocket url

The url is a requirement to create a new ngWebsocket. An instance is always created with a factory method by the $websocket service: in fact, it lets to make different websockets that are pointing to different urls.

Example of a basic instantiation:

Using Object configuration:

Following the explanation of the configuration object - {Type} PropertyName (default):

  • {Boolean} lazy (false): lazy initialization. A websocket can open the connection when ngWebsocket is instantiated with $websocket.$new (false) or afterwards with $open (false). For more information see Features - Lazy Initialization
  • {Boolean} reconnect (true): auto reconnect behaviour. A websocket can try to reopen the connection when is down (true) or stay closed (false). For more information see Features - Auto Reconnect
  • {Number} reconnectInterval (2000): auto reconnect interval. By default, a websocket try to reconnect after 2000 ms (2 seconds). For more information see Features - Auto Reconnect
  • {Boolean} enqueue (false): enqueue unsent messages. By default, a websocket discards messages when the connection is closed (false) but it can enqueue them and send afterwards the connection gets open back (true). For more information see Features - Enqueue Unsent Messages
  • {Boolean/Object} mock (false): mock a websocket server. By default, a websocket run only if the webserver socket is listening (false) but it can be useful to mock the backend to make the websocket working (true). For more information see Features - Mock Websocket Server


Websocket status constants:

  • $CONNECTING: the websocket is trying to open the connection
  • $OPEN: the websocket connection is open
  • $CLOSING: the websocket connection is closing
  • $CLOSED: the websocket connection is closed


There are custom events fired by ngWebsocket. They are useful to setup a listener for certain situations and behaviours:

  • $open: the websocket gets open
  • $close: the websocket gets closed
  • $error: an error occurred (callback params: {Error} error)
  • $message: the original message sent from the server (callback params: {String} message). Usually, it's a JSON encoded string containing the event to fire and the data to pass ({"event": "an event", "data": "some data"})

The other events are custom events, setup by the user itself.


Attach one or more handlers to a specific event.

Now the websocket is listening for 'my event' event and the handler 'myHandler' will be called when that event is sent by the websocket server. The same thing happens for the other two cases: each event handler is called one by one, starting from the first one, ending with the last one.



| Param | Type | Details | | --------- | -------- | ----------- | | event | String | the event to attach a listener | | handler/handlers | Function/Function[] | one or more handlers to invoke when the event is fired up |


| Type | Details | | -------- | ----------- | | ngWebsocket | the ngWebsocket |


Detach a handler from a specific event.

The above websocket has not listener attached at the end of the execution.



| Param | Type | Details | | --------- | -------- | ----------- | | event | String | the event to detach the listener |


| Type | Details | | -------- | ----------- | | ngWebsocket | the ngWebsocket |


Send an event to the websocket server.

It's possible to send a lonely event or attaching some data to it.

It's possible to send both simply (like strings and numbers) and complex data (like objects and arrays).



| Param | Type | Details | | --------- | -------- | ----------- | | event | String | the event to send | | data (optional) | String/Number/Object | the data to send with the event |


| Type | Details | | -------- | ----------- | | ngWebsocket | the ngWebsocket |


Open the websocket connection if it's closed.



| Type | Details | | -------- | ----------- | | ngWebsocket | the ngWebsocket |


It closes the websocket connection if it's open.



| Type | Details | | -------- | ----------- | | ngWebsocket | the ngWebsocket |


It returns the current status of the websocket connection. It's possible to use the websocket constants to make checks.



| Type | Details | | -------- | ----------- | | Number | a constant number representing the websocket connection readyState |


It returns if the websocket connection is open or closed.



| Type | Details | | -------- | ----------- | | Boolean | true if the connection is OPEN, false otherwise |


It returns if the websocket is mocked up or not.



| Type | Details | | -------- | ----------- | | Boolean | true if the ngWebsocket istance is mocked up, false otherwise |


If you need to develop or test your application without a real websocket backend server, you can setup a mockup of it with this feature. The only thing to do is to pass a configuration object during the ngWebsocket initialization:

Following the explanation of the configuration object - {Type} PropertyName (default)::

  • {Boolean/Object} mock (false): could be either a Boolean (default to false) or an object
  • {Number} openTimeout (500): timeout to make the internal websocket to get open
  • {Number} closeTimeout (1000): timeout to make the internal websocket to get closed
  • {Number} messageInterval (2000): the internal websocket sends enqueued message with this interval time
  • {Object/String} fixtures ({}): an object of fixtures, where the keys are the events and the values are the data to respond, or an url to retrieve remote fixtures via HTTP

Fixtures can mock both custom events and data:

Example with an url:


Wanna contribute, fella? That's the right place to find useful information!


  • improve and fix the documentation
  • test it
  • make some demos
  • use it
  • write new pieces of code
  • optimize it
  • find bugs

And don't forget to make pull requests, damn it!


Check out LICENSE file (MIT)

comments powered by Disqus
This page was last updated almost 4 years ago.