using System;
using Swan;
namespace EmbedIO.WebSockets.Internal
{
///
/// Represents the event data for the event.
///
///
///
/// That event occurs when the receives
/// a message or a ping if the
/// property is set to true.
///
///
/// If you would like to get the message data, you should access
/// the or property.
///
///
internal class MessageEventArgs : EventArgs
{
private readonly byte[] _rawData;
private string? _data;
private bool _dataSet;
internal MessageEventArgs(WebSocketFrame frame)
{
Opcode = frame.Opcode;
_rawData = frame.PayloadData.ApplicationData.ToArray();
}
internal MessageEventArgs(Opcode opcode, byte[] rawData)
{
if ((ulong)rawData.Length > PayloadData.MaxLength)
throw new WebSocketException(CloseStatusCode.TooBig);
Opcode = opcode;
_rawData = rawData;
}
///
/// Gets the message data as a .
///
///
/// A that represents the message data if its type is
/// text or ping and if decoding it to a string has successfully done;
/// otherwise, .
///
public string? Data
{
get
{
SetData();
return _data;
}
}
///
/// Gets a value indicating whether the message type is binary.
///
///
/// true if the message type is binary; otherwise, false.
///
public bool IsBinary => Opcode == Opcode.Binary;
///
/// Gets a value indicating whether the message type is ping.
///
///
/// true if the message type is ping; otherwise, false.
///
public bool IsPing => Opcode == Opcode.Ping;
///
/// Gets a value indicating whether the message type is text.
///
///
/// true if the message type is text; otherwise, false.
///
public bool IsText => Opcode == Opcode.Text;
///
/// Gets the message data as an array of .
///
///
/// An array of that represents the message data.
///
public byte[] RawData
{
get
{
SetData();
return _rawData;
}
}
internal Opcode Opcode { get; }
private void SetData()
{
if (_dataSet)
return;
if (Opcode == Opcode.Binary)
{
_dataSet = true;
return;
}
_data = _rawData.ToText();
_dataSet = true;
}
}
}