using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AIK.Common.StompNet { /// /// STOMP帧结构 /// public static class StompFrameHelper { private static readonly byte[] NullByte = { 0 }; public static byte[] BuildFrame(string command, Dictionary? headers = null, string? body = null) { var sb = new StringBuilder(); sb.Append(command).Append('\n'); if (headers != null) { foreach (var header in headers) { sb.Append($"{header.Key}:{header.Value}").Append("\n"); } } sb.Append("\n"); // 空行 sb.Append("\u0000"); // 结束符 var headerBytes = Encoding.UTF8.GetBytes(sb.ToString()); return headerBytes; } public static (string command, Dictionary headers, string body)? ParseFrame(byte[] data) { if (data.Length == 0 || data[data.Length - 1] != 0) return null; var text = Encoding.UTF8.GetString(data, 0, data.Length - 1); // 去掉 var parts = text.Split(new[] { "\r\n\r\n", "\n\n" }, 2, StringSplitOptions.None); if (parts.Length < 1) return null; var headerSection = parts[0]; var body = parts.Length > 1 ? parts[1] : ""; var lines = headerSection.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 0) return null; var command = lines[0].Trim(); var headers = new Dictionary(); for (int i = 1; i < lines.Length; i++) { var line = lines[i]; var idx = line.IndexOf(':'); if (idx > 0) { var key = line.Substring(0, idx).Trim(); var value = line.Substring(idx + 1).Trim(); headers[key] = value; } } return (command, headers, body); } } }