diff --git a/README.md b/README.md index 946bea4..9ff4d3f 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,40 @@ angular.module('MyCoolChainedWebApp', ['ngWebsocket']) }); }); ``` +Want to send a binary message? Set the 'binary' parameter to true. + +```javascript +'use strict'; + +angular.module('MyCoolChainedWebApp', ['ngWebsocket']) + .run(function ($websocket) { + var ws = $websocket.$new('ws://localhost:12345') + .$on('$open', function () { + console.log('Oh my gosh, websocket is really open! Fukken awesome!'); + + var data = new Uint8Array([21,31]); + + ws.binaryType = 'arraybuffer'; + + ws.$emit('ping', 'hi listening websocket server') // send a message to the websocket server + .$emit('pong', data, true); + }) + .$on('pong', function (data) { + console.log('The websocket server has sent the following data:'); + + if (data instanceof ArrayBuffer) { + console.log('A binary message of length', data.toArrayBuffer().byteLength; + } else { + console.log(data); + } + + ws.$close(); + }) + .$on('$close', function () { + console.log('Noooooooooou, I want to have more fun with ngWebsocket, damn it!'); + }); + }); +``` Your back-end team is lazy? No problem: we can do it on our own! diff --git a/ng-websocket.js b/ng-websocket.js index ca65608..80a33eb 100644 --- a/ng-websocket.js +++ b/ng-websocket.js @@ -214,20 +214,34 @@ return me; }; - me.$$send = function (message) { - if (me.$ready()) me.$$ws.send(JSON.stringify(message)); - else if (me.$$config.enqueue) me.$$queue.push(message); + me.$$send = function (message, binary) { + if (me.$ready()) { + if (binary === undefined || !binary) { + me.$$ws.send(JSON.stringify(message)); + } else { + me.$$ws.send(message); + } + } + else if (me.$$config.enqueue) { + me.$$queue.push(message); + } }; - me.$emit = function (event, data) { + me.$emit = function (event, data, binary) { if (typeof event !== 'string') throw new Error('$emit needs two parameter: a String and a Object or a String'); - var message = { - event: event, - data: data - }; + if (binary === undefined || !binary) { + + var message = { + event: event, + data: data + }; - me.$$send(message); + me.$$send(message); + } else { + // do not compose JSON message, send 'data' as-is + me.$$send(data, binary); + } return me; };