API Docs for: 0.0.1
Show:

File: src/link/Network.js

/**
 * @author Vsevolod Strukchinsky @floatdrop
 */

/* global msgpack */

/**
Network class.

This class represents transport between client link.js and server node-link.
Network layer is websockets which support binary encoding of messages wisg msgpack.

@example
	var network = new LINK.Network({binary: true});
	network.onmessage(function (message) { console.log(message); });
	network.onerror(function (error) { console.log("Error: " + error); });
	network.onclose(function (error) { console.log("Closed: " + error); })
	network.connect("localhost");
	
	// some code later

	network.close();

@class Network
@param config {Object}
@constructor
**/

LINK.Network = function (config) {
	this.config = config;
};

LINK.Network.constructor = LINK.Network;
LINK.Network.prototype = Object.create(Object.prototype);

/**
 * Creates new layer with name layerName above others layers.
 * @method connect
 * @param  host {String}
 * @param  port {Number}
 */

LINK.Network.prototype.connect = function (host, port) {
	this.socket = new WebSocket("ws://" + this.host + (port ? ":" + port : ""));
};

/**
 * Creates new layer with name layerName above others layers.
 * @method onmessage
 * @param  callback {Function}
 */

LINK.Network.prototype.onmessage = function (callback) {
	if (this.socket) this.socket.onmessage = function (event) {
		if (typeof event.data === "string") {
			callback(JSON.parse(event.data));
		} else {
			var reader = new FileReader();
			reader.readAsArrayBuffer(event.data);
			reader.onloadend = function () {
				var message = msgpack.decode(this.result);
				callback(message);
			};
		}
	};
};

/**
 * Creates new layer with name layerName above others layers.
 * @method onopen
 * @param  callback {Function}
 */
LINK.Network.prototype.onopen = function (callback) {
	if (this.socket) this.socket.onopen = callback;
};

/**
 * Creates new layer with name layerName above others layers.
 * @method onerror
 * @param  callback {Function}
 */
LINK.Network.prototype.onerror = function (callback) {
	if (this.socket) this.socket.onerror = callback;
};

/**
 * Creates new layer with name layerName above others layers.
 * @method onclose
 * @param  callback {Function}
 */
LINK.Network.prototype.onclose = function (callback) {
	if (this.socket) this.socket.onclose = callback;
};

/**
 * Creates new layer with name layerName above others layers.
 * @method send
 * @param  message {Object}
 */
LINK.Network.prototype.send = function (message) {
	if (this.socket) {
		this.socket.send(this.config.binary ? msgpack.encode(message) : JSON.stringify(message));
	}
};

/**
 * Creates new layer with name layerName above others layers.
 * @method close
 * @param  layerName {String}
 */
LINK.Network.prototype.close = function() {
	if (this.socket) {
		this.socket.close();
	}
};