// -----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// -----------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.Webserver
{
using System;
using System.IO;
using System.Net.WebSockets;
///
/// Static class that defines extensions used to serialize objects into web socket messages.
///
public static class WebSocketMessageExtensions
{
///
/// Serializes object as a UTF8-encoded JSON string and creates a web socket message to
/// be sent over the wire.
///
///
/// Type of object to serialize and send as a message.
///
///
/// Object to serialize and send as a message.
///
///
/// Web socket message ready to be sent.
///
public static WebSocketMessage ToTextMessage(this T obj)
{
using (var stream = new MemoryStream())
{
obj.ToJson(stream);
return new WebSocketMessage(new ArraySegment(stream.GetBuffer(), 0, (int)stream.Length), WebSocketMessageType.Text);
}
}
///
/// Takes an array of bytes representing UTF8-encoded text and creates a web socket message
/// to be sent over the wire.
///
///
/// Array of bytes representing UTF8-encoded text.
///
///
/// Web socket message ready to be sent.
///
public static WebSocketMessage ToTextMessage(this byte[] textData)
{
return new WebSocketMessage(new ArraySegment(textData), WebSocketMessageType.Text);
}
///
/// Takes an array of bytes representing binary data and creates a web socket message
/// to be sent over the wire.
///
///
/// Array of bytes representing binary data.
///
///
/// Web socket message ready to be sent.
///
public static WebSocketMessage ToBinaryMessage(this byte[] data)
{
return new WebSocketMessage(new ArraySegment(data), WebSocketMessageType.Binary);
}
}
}