Skip to content

Instantly share code, notes, and snippets.

@XSockets
Last active August 29, 2015 14:00
Show Gist options
  • Save XSockets/11210149 to your computer and use it in GitHub Desktop.
Save XSockets/11210149 to your computer and use it in GitHub Desktop.
Sending binary message with metadata from C# client to XSockets server
//client memeber is of type IXSocketClient that is connected to controller "foo"
//Read a dummy file from disk
var bytes = File.ReadAllBytes(@"c:\temp\HelloWorld.txt");
//Create message with the custom helper "CreateBinaryMessage" and add the metadata of choice
var binaryMessage = client.CreateBinaryMessage(bytes, new FileInfo { FileName = "HelloWorld.txt" });
//Send the binary message
client.Send(binaryMessage);
public static class BinaryMessageExtentions
{
public static BinaryArgs CreateBinaryMessage(this IXSocketClient client, IList<byte> buffer, object metadata, string @event = "binary")
{
//Transform metadata into JSON
var jsonMeta = client.Serializer.SerializeToString(metadata);
//Add metadata to a TextArgs object
var json = client.Serializer.SerializeToString(new TextArgs(jsonMeta, @event));
//Set the metadata as header in the binary message
var ms = new List<byte>();
var payload = json;
var header = BitConverter.GetBytes((Int64)payload.Length);
ms.AddRange(header);
ms.AddRange(Encoding.UTF8.GetBytes(payload));
ms.AddRange(buffer);
return new BinaryArgs(ms);
}
}
//Serverside controller where the binary message arrives...
public class Foo : XSocketController
{
public override void OnMessage(IBinaryArgs binaryArgs)
{
//Convert the binaryArgs to a combinedMessage
var bm = binaryArgs.AsCombinedMessage();
//Get the metadata included from client
var fileInfo = bm.Extract<FileInfo>();
//Get the filecontent
var file = Encoding.UTF8.GetString(bm.BinaryArgs.data.ToArray());
//Add logic for saving, sending back etc...
}
}
//Stupid metadata class know both by server and client
public class FileInfo
{
public string FileName { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment