using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
using Newtonsoft.Json.Linq;
|
|
namespace Sodao.FastSocket.Server.Protocol
|
{
|
public sealed class HxProtocol : IProtocol<Messaging.HxMessage>
|
{
|
static private readonly string CHECK_KEY1 = "message_id";
|
static private readonly string CHECK_KEY2 = "message_type";
|
static private readonly string ENDOP = "#!HxSEP!#";
|
|
static private readonly string[] SPLITER =
|
new string[] { ENDOP };
|
/// <summary>
|
/// parse
|
/// </summary>
|
/// <param name="connection"></param>
|
/// <param name="buffer"></param>
|
/// <param name="maxMessageSize"></param>
|
/// <param name="readlength"></param>
|
/// <returns></returns>
|
/// <exception cref="BadProtocolException">bad thrift protocol</exception>
|
public Messaging.HxMessage Parse(SocketBase.IConnection connection, ArraySegment<byte> buffer,
|
int maxMessageSize, out int readlength)
|
{
|
if (buffer.Count < 2)
|
{
|
readlength = 0;
|
return null;
|
}
|
|
string command = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
|
if (!command.Contains(SPLITER[0]))
|
{
|
readlength = 0;
|
return null;
|
}
|
var arr = command.Split(SPLITER, StringSplitOptions.RemoveEmptyEntries);
|
if (arr.Length == 0)
|
{
|
readlength = 0;
|
return null;
|
}
|
if (arr[0].Length > 10 && arr[0].Contains(CHECK_KEY1) && arr[0].Contains(CHECK_KEY2))
|
{
|
readlength = arr[0].Length + ENDOP.Length;// - buffer.Offset;
|
}
|
else { readlength = 0; }
|
|
try
|
{
|
// hxj 2023-11-22 : 去掉 arr[0] 开头非 json部分
|
string jsonSource = arr[0];
|
while (!jsonSource.StartsWith("{"))
|
{
|
jsonSource = jsonSource.Substring(jsonSource.IndexOf("{"));
|
}
|
Messaging.HxMessage msg = new Messaging.HxMessage(jsonSource);
|
return msg;
|
}
|
catch (Exception ex)
|
{
|
readlength = arr[0].Length;
|
return null;
|
}
|
|
}
|
}
|
}
|