Esempio n. 1
0
        /// <summary>
        /// 服务器端收包处理
        /// </summary>
        /// <param name="data"></param>
        /// <param name="OnHeart"></param>
        /// <param name="OnUnPackage"></param>
        /// <param name="onFile"></param>
        public void Pack(byte[] data, Action <DateTime> onHeart, Action <ISocketProtocal> onUnPackage, Action <byte[]> onFile)
        {
            lock (_locker)
            {
                _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 SocketProtocal()
                        {
                            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 SocketProtocal()
                            {
                                BodyLength = bodyLen, Type = (byte)type, Content = GetContent(buffer, P_Head, (int)bodyLen)
                            };
                            _buffer.RemoveRange(0, (int)(P_Head + bodyLen));
                            bodyLen = 0;
                            onUnPackage?.Invoke(sm);
                        }
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
Esempio n. 2
0
        public static SocketProtocal Parse(byte[] data, SocketProtocalType type)
        {
            var msg = new SocketProtocal();

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

            msg.Type = (byte)type;

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

            return(msg);
        }