Binary data - XSockets/XSockets.NET-4.0 GitHub Wiki
XSockets has supported binary messages for a long time, but in 4.0 we have made it even easier than before.
Lets say that we have a file c:\temp\xfile.txt
with the text This file was sent with XSockets.NET
and we want to send that file to the server.
Server
//using XSockets.Core.XSocket;
//using XSockets.Core.Common.Socket.Event.Interface;
public void MyFile(IMessage message)
{
var filecontent = Encoding.UTF8.GetString(message.Blob.ToArray());
}
Clients
- JavaScript
// Create a simple Array buffer and fill it with "something"
var arrayBuffer = new ArrayBuffer(10);
// Send the binary data to XSockets
conn.controller("chat").invokeBinary("myfile",blob);
- C#
var blob = File.ReadAllBytes(@"c:\temp\xfile.txt");
conn.Controller("chat").Invoke("myfile", blob);
If we want to attach metadata about the binary data that is easy to do. Just pass along the object representing the metadata and XSockets will let you extract that data on the server.
Server
//simple class for holding metadata about a file
public class FileInfo
{
public string Name {get;set;}
}
//using XSockets.Core.XSocket;
//using XSockets.Core.Common.Socket.Event.Interface;
public void MyFile(IMessage message)
{
var filecontent = Encoding.UTF8.GetString(message.Blob.ToArray());
var metadata = message.Extract<FileInfo>();
}
Just use Extract<T>
to get back to metadata attached to the binary data.
Clients
- JavaScript
// Create a simple Array buffer and fill it with "something"
var arrayBuffer = new ArrayBuffer(10);
// Send the binary data and metadata to XSockets
conn.controller("chat").invokeBinary("myfile",blob,{Name:"xfile.txt"});
- C#
var blob = File.ReadAllBytes(@"c:\temp\xfile.txt");
conn.Controller("chat").Invoke("myfile", blob, new {Name="xfile.txt"});
If you want to send for example and image from the server to the clients it can be done like this. The name of the controller will be "Chat" and the name (or topic) is "myimage".
Server
var blob = File.ReadAllBytes(@"c:\temp\someimage.jpg");
this.InvokeToAll(blob,"myimage");
Clients
- JavaScript
conn.controller("chat").on("myimage") = function (b) {
var uint8Array = new Uint8Array(b.binary);
var arrayBuffer = uint8Array.buffer;
var blob = new Blob([arrayBuffer], { type: "image/jpg" });
var blobUrl = window.URL.createObjectURL(blob);
$("img").attr("src", blobUrl);
};
- C#
conn.Controller("chat").On<IMessage>("myimage", message =>
{
var ms = new MemoryStream(message.Blob.ToArray());
var img = Image.FromStream(ms);
//Do something with the image...
});