schangxiang@126.com
2025-11-04 f5ed29dc26c7cd952d56ec5721a2efc43cd25992
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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;
            }
 
        }
    }
}