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
using System;
using System.Linq;
using System.Text;
 
namespace Sodao.FastSocket.Server.Protocol
{
    /// <summary>
    /// 命令行协议
    /// </summary>
    public sealed class CommandLineProtocol : IProtocol<Messaging.CommandLineMessage>
    {
        static private readonly string[] SPLITER =
            new string[] { " " };
 
        /// <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 command line protocol</exception>
        public Messaging.CommandLineMessage Parse(SocketBase.IConnection connection, ArraySegment<byte> buffer,
            int maxMessageSize, out int readlength)
        {
            if (buffer.Count < 2)
            {
                readlength = 0;
                return null;
            }
 
            //查找\r\n标记符
            for (int i = buffer.Offset, len = buffer.Offset + buffer.Count; i < len; i++)
            {
                if (buffer.Array[i] == 13 && i + 1 < len && buffer.Array[i + 1] == 10)
                {
                    readlength = i + 2 - buffer.Offset;
 
                    if (readlength == 2) return new Messaging.CommandLineMessage(string.Empty);
                    if (readlength > maxMessageSize) throw new BadProtocolException("message is too long");
 
                    string command = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, readlength - 2);
                    var arr = command.Split(SPLITER, StringSplitOptions.RemoveEmptyEntries);
 
                    if (arr.Length == 0) return new Messaging.CommandLineMessage(string.Empty);
                    if (arr.Length == 1) return new Messaging.CommandLineMessage(arr[0]);
                    return new Messaging.CommandLineMessage(arr[0], arr.Skip(1).ToArray());
                }
            }
            readlength = 0;
            return null;
        }
    }
}