Ejemplo n.º 1
0
        public void Unpack(byte[] data, Action <ISocketProtocal> unpackCallback, Action <DateTime> onHeart = null, Action <byte[]> onFile = null)
        {
            _buffer.AddRange(data);

            while (_buffer.Count >= P_Head)
            {
                var buffer = _buffer.ToArray();

                var bodyLen = GetLength(buffer);

                var type = GetType(buffer);

                if (bodyLen == 0 && type == SocketProtocalType.Heart) //空包认为是心跳包
                {
                    var sm = new BaseSocketProtocal()
                    {
                        BodyLength = bodyLen, Type = (byte)type
                    };
                    _buffer.Clear();
                    onHeart?.Invoke(DateTimeHelper.Now);
                }
                else if (buffer.Length >= P_Head + bodyLen)
                {
                    if (type == SocketProtocalType.BigData)
                    {
                        var content = GetContent(buffer, P_Head, (int)bodyLen);
                        _buffer.RemoveRange(0, (int)(P_Head + bodyLen));
                        bodyLen = 0;
                        onFile?.Invoke(content);
                    }
                    else
                    {
                        var sm = new BaseSocketProtocal()
                        {
                            BodyLength = bodyLen, Type = (byte)type, Content = GetContent(buffer, P_Head, (int)bodyLen)
                        };
                        _buffer.RemoveRange(0, (int)(P_Head + bodyLen));
                        bodyLen = 0;
                        unpackCallback?.Invoke(sm);
                    }
                }
                else
                {
                    return;
                }
            }
        }
Ejemplo n.º 2
0
        public static BaseSocketProtocal Parse(byte[] data, SocketProtocalType type)
        {
            var msg = new BaseSocketProtocal();

            if (data != null)
            {
                msg.BodyLength = data.Length;
            }
            else
            {
                msg.BodyLength = 0;
            }

            msg.Type = (byte)type;

            if (msg.BodyLength > 0)
            {
                msg.Content = data;
            }

            return(msg);
        }