0.0.2 • Published 8 years ago

ng-ws v0.0.2

Weekly downloads
3
License
MIT
Repository
github
Last release
8 years ago

ng-ws

AngularJS HTML5 WebSocket wrapper module for HTML5 WebSocket with aditional features!

Index

Introduction

ng-ws is a library that provides a provider to handle HTML5 WebSocket with aditional features

Requirements

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

Installation

Use npm to install this module:

$ npm install ng-ws

Use Bower to install this module:

$ bower install ng-ws

Usage

After the Installation, require it in your Angular application.

Firstly, in your index.html:

<html>
    <head>
        <script src="bower_components/ng-ws/ng-ws.js"></script>
    </head>
</html>

or

<html>
    <head>
        <script src="node_modules/ng-ws/ng-ws.js"></script>
    </head>
</html>

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

    'use strict';

    angular.module('MyApp', ['ng-ws']);

Usage,

Tutorial

'use strict';

angular.module('MyApp', ['ng-ws'])
    .run(function ($ws) {
        var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		}); // instance of ws, only the url is mandatory, others will be with default values

        ws.on('open', function () {
            console.log('Connection open...');

            ws.send('message to server'); // send a message to the websocket server

            var data = {
                id: 1,
                text: 'message to server'
                details:[{
                    id: 11,
                    message: 'message to server 2'
                }, {
				    id: 12,
                    message: 'message to server 3'
				}]
            };

            ws.send(JSON.stringify(data);
			//or
			ws.send(JSON.stringify({ event: 'updateData', data: data }));
        });

        ws.on('message', function (message) { // when receiving message from server
            console.log('message from server with data:');
            console.log(message.data);
			//or if json format
			//console.log(JSON.parse(message.data));
        });

        ws.on('close', function (e) { // when connection closed
            console.log('connection closed...');
        });
    });

Features

ng-ws has some aditional features

reconnect

You don't have to reconnect manually if connection down for any reason, except closing by you for sure, for exmaple network down, server down, .. Interval we keep trying to reconnect for you based on the configured reconnectInterval, till the connection opened

By default, reconnect is enabled, and default interval is 2000 milliseconds

var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		}); // instance of ws, only the url is mandatory, others will be with default values

lazyOpen

You can only initialize the connection and open the connection later, or switching between close and open. By default, lazyOpen is disabled

var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: true,
            protocols: null,
            enqueue: false
		}); // instance of ws, only the url is mandatory, others will be with default values
		
	//ws.open();
	//ws.close();

enqueue

Incase connection not openned, the sent message to server will be queued MEMORY till the connection is open, messages will be flushed to server autimaticlly By default, enqueue is disabled

var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: true
		}); // instance of ws, only the url is mandatory, others will be with default values

API

methods:

init

initialize websocket instance with custom configuration, only the 'url' is mandatory, other fields are optionals:

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
});

Usage

$ws.init({
	url: 'ws://someUrl',
	reconnect: true,
	reconnectInterval: 2000,
	lazyOpen: false,
	protocols: null,
	enqueue: false
});

Arguments

ParamTypeDetails
configObjectws configuration

Returns

TypeDetails
wsthe websocket wrapper

open

open websocket instance connection if the connection closed or if you used 'lazyOpen' in 'init' method:

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
		
	ws.open();
});

Usage

ws.open();

send

send data to websocket server:

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
		
	ws.send('some data');
});

Usage

ws.send('some data');

Arguments

ParamTypeDetails
dataString or ArrayBuffer or Blobdata to be sent to server

close

close websocket connection:

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
		
	ws.close();
});

Usage

ws.close(code, reason);

Arguments

ParamTypeDetails
codeunsigned shortAn optional numeric value indicating the status code explaining why the connection is being closed, status codes
reasonstringAn optional human-readable string explaining why the connection is closing

getState

get websocket state:

valueDetails
-1NOT_INITIALIZED
0CONNECTING
1OPEN
2CLOSING
3CLOSED
angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
		
	var state = ws.getState();
});

Usage

var state = ws.getState();

Returns

TypeDetails
intwebsocket connection state

updateConfig

update configuration, this will close the connection and initialize it with new config:

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
		
	ws.updateConfig({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 500,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
});

Usage

ws.updateConfig({
	url: 'ws://someUrl',
	reconnect: true,
	reconnectInterval: 500,
	lazyOpen: false,
	protocols: null,
	enqueue: false
});

Arguments

ParamTypeDetails
configObjectws configuration

on

Attach a handler to an event:

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
		
	ws.on('open', function(){
		console.log('Connection open ...');
	});
});

Usage

ws.on('eventName', function(e) { ; });

Arguments

ParamTypeDetails
eventNameStringevent name
handlerFunctionevent handler function

un

Unattach handler from event

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: false
		});
		
	var onOpen = function(e) {
	};
	
	ws.on('open', onOpen);
	
	ws.un('open', onOpen);
});

Usage

ws.un('eventName', function(){ ; });

Arguments

ParamTypeDetails
eventNameStringevent name
handlerFunctionevent handler function

Memders

queue

the unset data to the server, in case enqueue config value enabled and the connection not open:

angular.config(function ($ws) {
    var ws = $ws.init({
			url: 'ws://someUrl',
			reconnect: true,
            reconnectInterval: 2000,
            lazyOpen: false,
            protocols: null,
            enqueue: true
		});
	
	console.log(ws.queue.length);
});

Usage

ws.queue;

Description

TypeDetails
Arrayun sent messages to server

events:

HTML5 WebSocket events

open

An event listener to be called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data. The event is a simple one with the name "open".

message

An event listener to be called when a message is received from the server. The listener receives a MessageEvent named "message".

close

An event listener to be called when the WebSocket connection's readyState changes to CLOSED. The listener receives a CloseEvent named "close".

error

An event listener to be called when an error occurs. This is a simple event named "error".

License

Check out LICENSE file (MIT)