Skip to content

Instantly share code, notes, and snippets.

@XSockets
Last active December 29, 2015 16:28
Show Gist options
  • Save XSockets/7697294 to your computer and use it in GitHub Desktop.
Save XSockets/7697294 to your computer and use it in GitHub Desktop.
XSockets support sending text data together with binary data over websockets. Event though the protocol does no support it... Try that with somethingR ;)
//Create a new XSockets text message.... the event is foo... The data is {lion:'grrr', p:Date()}
var myJson = new XSockets.Message("foo", { lion: 'grrr', p: Date() });
//Create a XSockets binary message and attach the text to it... (we call canvasToBuffer() to get hold of some data)
var binaryMessage = new XSockets.BinaryMessage(myJson, canvasToBuffer(),
//The callback where we have data in the arrayBuffer...
function (arrayBuffer) {
// Okey, the buffer is created and wrapped in our simple "subprotocol".... send it!
ws.send(arrayBuffer.buffer);
});
using System.Diagnostics;
using XSockets.Core.Common.Socket.Event.Interface;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
namespace XSockets.Test.Controllers
{
//A custom object that reflect the JSON being sent...
public class CustomData
{
public string lion { get; set; }
public string p { get; set; }
}
public class MyBinaryController : XSocketController
{
//Override the method where the binary data will arrive...
public override void OnMessage(IBinaryArgs binaryArgs)
{
//Convert the binaryArgs to a combinedMessage (will contain both ITextArgs and IBinaryArgs)
var bm = binaryArgs.AsCombinedMessage();
//Get the IBinaryArgs (the arraybuffer from the canvas)
//bm.BinaryArgs
//Get the ITextArgs (the JSON attached with the binary message)
//bm.TextArgs
//The interesting part... Get the strongly typed object passed with the arraybuffer
var myCustomObject = bm.Extract<CustomData>();
Debug.WriteLine(myCustomObject.lion);
Debug.WriteLine(myCustomObject.p);
//A shortcut would ofcourse be
// var customObject = binaryArgs.AsCombinedMessage().Extract<CustomData>();
}
}
}
/*This will ofcourse output something like...
grrr
Thu Nov 28 2013 20:50:40 GMT+0100 (W. Europe Standard Time)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment