Last active
December 18, 2015 21:39
-
-
Save ismasan/5848735 to your computer and use it in GitHub Desktop.
WebSocket wrapper for Plumber.js https://github.com/ismasan/plumber.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* WebSocket wrapper for Plumber.js | |
* | |
* https://github.com/ismasan/plumber.js | |
* | |
* Reconnect on close with 5 seconds delay | |
* | |
* Assumes WebSocket messages are JSON strings | |
* | |
* Usage: | |
* | |
* // Instantiate | |
* var socket = new SocketRepository('ws://some.server.com') | |
* | |
* // Forward incoming messages to other pipes in your app | |
* socket.pipe(someOtherPlumberPipe) | |
* | |
* // Send data down the socket | |
* socket.add(someStruct) | |
*/ | |
var SocketRepository = (function () { | |
var reconnect_delay = 5000; | |
/* Private stuff | |
------------------------------------*/ | |
function log() { | |
console.log('socket:', arguments) | |
} | |
function logFor(evtName) { | |
return function () { | |
console.log('socket:', evtName, arguments) | |
} | |
} | |
function onclose () { | |
log('closed. Reconnect in ', reconnect_delay) | |
setTimeout($.proxy(this.__connect, this), reconnect_delay) | |
} | |
function dispatch (evt) { | |
var data = JSON.parse(evt.data) | |
var struct = new Plumber.Struct(data) | |
this.add(struct) | |
} | |
/* Socket repository constructor | |
---------------------------------------------------*/ | |
var SocketRepository = Plumber.Pipe.extend({ | |
initialize: function (host) { | |
this.host = host; | |
this.__connect() | |
}, | |
/** | |
* Sends a serialized struct down the websocket | |
* | |
* @param {Struct} struct The Struct instance being forwarded. | |
* @param {$.Deferred} promise to be fulfilled on success (or immediatly for fire-and-forget behaviour) | |
*/ | |
_add: function (struct, promise) { | |
// Insert your custom serialization here, or queue and wait for socket to connect, etc. | |
this.ws.send(JSON.stringify(struct.attributes)) | |
// Do not resolve if you don't want this pipe to forward to other pipes. | |
promise.resolve(struct) | |
}, | |
__connect: function () { | |
log('connecting') | |
this.ws = new WebSocket(this.host) | |
this.ws.onopen = logFor('open') | |
this.ws.onclose = $.proxy(onclose, this) | |
this.ws.onmessage = $.proxy(dispatch, this) | |
} | |
}) | |
return SocketRepository | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment