using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NEIntelligentControl2.Service.WebSocket
{
///
/// WebSocket消息
///
public class StompMessage
{
private readonly Dictionary _headers = new Dictionary();
///
/// Initializes a new instance of the class.
///
/// The command.
public StompMessage(string command)
: this(command, string.Empty)
{
}
///
/// Initializes a new instance of the class.
///
/// The command.
/// The body.
public StompMessage(string command, string body)
: this(command, body, new Dictionary())
{
}
///
/// Initializes a new instance of the class.
///
/// The command.
/// The body.
/// The headers.
internal StompMessage(string command, string body, Dictionary headers)
{
Command = command;
Body = body;
_headers = headers;
this["content-length"] = body.Length.ToString();
}
public Dictionary Headers
{
get { return _headers; }
}
///
/// Gets the body.
///
public string Body { get; private set; }
///
/// Gets the command.
///
public string Command { get; private set; }
///
/// Gets or sets the specified header attribute.
///
public string this[string header]
{
get { return _headers.ContainsKey(header) ? _headers[header] : string.Empty; }
set { _headers[header] = value; }
}
///
/// 转换为字符串
///
///
public override string ToString()
{
var buffer = new StringBuilder();
buffer.Append(Command + "\n");
if (Headers != null)
{
foreach (var header in Headers)
{
buffer.Append(header.Key + ":" + header.Value + "\n");
}
}
buffer.Append("\n");
buffer.Append(Body);
buffer.Append('\0');
return buffer.ToString();
}
///
/// 解析消息
///
internal static StompMessage Deserialize(string data)
{
var reader = new System.IO.StringReader(data);
var command = reader.ReadLine();
var headers = new Dictionary();
var header = reader.ReadLine();
while (!string.IsNullOrEmpty(header))
{
var split = header.Split(':');
if (split.Length == 2) headers[split[0].Trim()] = split[1].Trim();
header = reader.ReadLine() ?? string.Empty;
}
var body = reader.ReadToEnd() ?? string.Empty;
body = body.TrimEnd('\r', '\n', '\0');
return new StompMessage(command, body, headers);
}
}
}