Exemplo n.º 1
0
        internal long LoadResponse(HttpMethod method)
        {
            Method                   = method;
            Address                  = _request.Address;
            HasError                 = false;
            MessageBodyLoaded        = false;
            KeepAliveTimeout         = null;
            MaximumKeepAliveRequests = null;
            _headers.Clear();
            _rawCookies.Clear();
            if (_request.Cookies != null && !_request.Cookies.IsLocked)
            {
                Cookies = _request.Cookies;
            }
            else
            {
                Cookies = new CookieDictionary();
            }
            if (_receiverHelper == null)
            {
                _receiverHelper = new ReceiverHelper(_request.TcpClient.ReceiveBufferSize);
            }
            _receiverHelper.Init(_request.ClientStream);
            try
            {
                ReceiveStartingLine();
                ReceiveHeaders();
                RedirectAddress          = GetLocation();
                CharacterSet             = GetCharacterSet();
                ContentLength            = GetContentLength();
                ContentType              = GetContentType();
                KeepAliveTimeout         = GetKeepAliveTimeout();
                MaximumKeepAliveRequests = GetKeepAliveMax();
            }
            catch (Exception ex)
            {
                HasError = true;
                if (ex is IOException)
                {
                    throw NewHttpException(Resources.HttpException_FailedReceiveResponse, ex);
                }
                throw;
            }
            if (ContentLength == 0 || Method == HttpMethod.HEAD || StatusCode == HttpStatusCode.Continue || StatusCode == HttpStatusCode.NoContent || StatusCode == HttpStatusCode.NotModified)
            {
                MessageBodyLoaded = true;
            }
            long num = _receiverHelper.Position;

            if (ContentLength > 0)
            {
                num += ContentLength;
            }
            return(num);
        }
Exemplo n.º 2
0
        private void OnSendButton(object param)
        {
            if (param is string)
            {
                string str = (string)param;
                if (string.IsNullOrEmpty(str))
                {
                    Debug.LogErrorFormat("OnSendButton str IsNullOrEmpty");
                    return;
                }

                MsgPerson p = new MsgPerson();
                p.Name  = "huangqiaoping_hahaha";
                p.Email = "*****@*****.**";
                p.Id    = 222;

                IBaseMessage msg = ReceiverHelper.PopMessage();
                msg.WriteIn(p, DefineProtobuf.MSG_PERSON);
                CoreModules.netMDL.SendMessage(msg);
                Debug.LogErrorFormat("OnSendButton str = {0}", str);
            }
        }
Exemplo n.º 3
0
 public ZipWraperStream(Stream baseStream, ReceiverHelper receiverHelper)
 {
     _baseStream     = baseStream;
     _receiverHelper = receiverHelper;
 }
Exemplo n.º 4
0
 public ZipWraperStream(Stream baseStream, ReceiverHelper receiverHelper)
 {
     _baseStream = baseStream;
     _receiverHelper = receiverHelper;
 }
Exemplo n.º 5
0
 public HttpResponseStream(Stream baseStream,
     ReceiverHelper receiverHelper, Action<Exception> endWrite)
 {
     _baseStream = baseStream;
     _receiverHelper = receiverHelper;
     _endWrite = endWrite;
 }
Exemplo n.º 6
0
        internal void LoadResponse(HttpMethod method)
        {
            HasError = false;
            Address = _request.Address;
            Method = method;

            MessageBodyLoaded = false;

            _receiverHelper = new ReceiverHelper(
                _request.ClientStream, _request.TcpClient.ReceiveBufferSize);

            try
            {
                ReceiveStartingLine();

                _headers.Clear();

                if (_request.Cookies != null && !_request.Cookies.IsLocked)
                {
                    Cookies = _request.Cookies;
                }
                else
                {
                    Cookies = new CookieDictionary();
                }

                ReceiveHeaders();

                CharacterSet = GetCharacterSet();
                ContentLength = GetContentLength();
                ContentType = GetContentType();
            }
            catch (Exception ex)
            {
                HasError = true;

                if (ex is IOException)
                {
                    throw NewHttpException(
                        Resources.HttpException_FailedReceiveResponse, ex);
                }

                throw;
            }

            // Если пришёл ответ без тела сообщения.
            if (Method == HttpMethod.HEAD || StatusCode == HttpStatusCode.Continue ||
                StatusCode == HttpStatusCode.NoContent || StatusCode == HttpStatusCode.NotModified)
            {
                MessageBodyLoaded = true;
            }
        }
Exemplo n.º 7
0
        // Загружает ответ и возвращает размер ответа в байтах.
        internal long LoadResponse(HttpMethod method)
        {
            Method = method;
            Address = _request.Address;

            HasError = false;
            MessageBodyLoaded = false;

            _headers.Clear();
            _rawCookies.Clear();

            if (_request.Cookies != null && !_request.Cookies.IsLocked)
            {
                Cookies = _request.Cookies;
            }
            else
            {
                Cookies = new CookieDictionary();
            }

            if (_receiverHelper == null)
            {
                _receiverHelper = new ReceiverHelper(
                    _request.TcpClient.ReceiveBufferSize);
            }

             _receiverHelper.Init(_request.ClientStream);

            try
            {
                ReceiveStartingLine();

                ReceiveHeaders();

                RedirectAddress = GetLocation();
                CharacterSet = GetCharacterSet();
                ContentLength = GetContentLength();
                ContentType = GetContentType();
            }
            catch (Exception ex)
            {
                HasError = true;

                if (ex is IOException)
                {
                    throw NewHttpException(Resources.HttpException_FailedReceiveResponse, ex);
                }

                throw;
            }

            // Если пришёл ответ без тела сообщения.
            if (ContentLength == 0 ||
                Method == HttpMethod.HEAD || Method == HttpMethod.DELETE ||
                StatusCode == HttpStatusCode.Continue || StatusCode == HttpStatusCode.NoContent ||
                StatusCode == HttpStatusCode.NotModified)
            {
                MessageBodyLoaded = true;
            }

            long responseSize = _receiverHelper.Position;

            if (ContentLength > 0)
            {
                responseSize += ContentLength;
            }

            return responseSize;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Пропускает тело сообщения. Данный метод следует вызвать, если не требуется тело сообщения.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Вызов метода из ошибочного ответа.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public void None()
        {
            #region Проверка состояния

            if (HasError)
            {
                throw new InvalidOperationException(
                    Resources.InvalidOperationException_HttpResponse_HasError);
            }

            #endregion

            if (MessageBodyLoaded)
            {
                return;
            }

            if (ConnectionClosed())
            {
                _request.Dispose();
                _receiverHelper = null;
            }
            else
            {
                try
                {
                    IEnumerable<BytesWraper> source = GetMessageBodySource();

                    foreach (BytesWraper bytes in source)
                    {
                        _request.ReportBytesReceived(bytes.Length, ContentLength);
                    }
                }
                catch (Exception ex)
                {
                    HasError = true;

                    if (ex is IOException || ex is InvalidOperationException)
                    {
                        throw NewHttpException(Resources.HttpException_FailedReceiveMessageBody, ex);
                    }

                    throw;
                }
                finally
                {
                    _receiverHelper = null;
                }
            }

            MessageBodyLoaded = true;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Загружает тело сообщения и сохраняет его в новый файл по указанному пути. Если файл уже существует, то он будет перезаписан.
        /// </summary>
        /// <param name="path">Путь к файлу, в котором будет сохранено тело сообщения.</param>
        /// <exception cref="System.InvalidOperationException">Вызов метода из ошибочного ответа.</exception>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="path"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="path"/> является пустой строкой, содержит только пробелы или содержит недопустимые символы.</exception>
        /// <exception cref="System.IO.PathTooLongException">Указанный путь, имя файла или и то и другое превышает наибольшую возможную длину, определенную системой. Например, для платформ на основе Windows длина пути не должна превышать 248 знаков, а имена файлов не должны содержать более 260 знаков.</exception>
        /// <exception cref="System.IO.FileNotFoundException">Значение параметра <paramref name="path"/> указывает на несуществующий файл.</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">Значение параметра <paramref name="path"/> указывает на недопустимый путь.</exception>
        /// <exception cref="System.IO.IOException">При открытии файла возникла ошибка ввода-вывода.</exception>
        /// <exception cref="System.Security.SecurityException">Вызывающий оператор не имеет необходимого разрешения.</exception>
        /// <exception cref="System.UnauthorizedAccessException">Операция чтения файла не поддерживается на текущей платформе.</exception>
        /// <exception cref="System.UnauthorizedAccessException">Значение параметра <paramref name="path"/> определяет каталог.</exception>
        /// <exception cref="System.UnauthorizedAccessException">Вызывающий оператор не имеет необходимого разрешения.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public void ToFile(string path)
        {
            #region Проверка состояния

            if (HasError)
            {
                throw new InvalidOperationException(
                    Resources.InvalidOperationException_HttpResponse_HasError);
            }

            #endregion

            #region Проверка параметров

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            #endregion

            if (MessageBodyLoaded)
            {
                return;
            }

            try
            {
                using (var fStream = new FileStream(path, FileMode.Create))
                {
                    IEnumerable<BytesWraper> source = GetMessageBodySource();

                    foreach (BytesWraper bytes in source)
                    {
                        fStream.Write(bytes.Value, 0, bytes.Length);
                        _request.ReportBytesReceived(bytes.Length, ContentLength);
                    }
                }
            }
            #region Catch's

            catch (ArgumentException ex)
            {
                throw ExceptionHelper.WrongPath("path", ex);
            }
            catch (NotSupportedException ex)
            {
                throw ExceptionHelper.WrongPath("path", ex);
            }
            catch (Exception ex)
            {
                HasError = true;

                if (ex is IOException || ex is InvalidOperationException)
                {
                    throw NewHttpException(Resources.HttpException_FailedReceiveMessageBody, ex);
                }

                throw;
            }

            #endregion
            finally
            {
                _receiverHelper = null;
            }

            if (ConnectionClosed())
            {
                _request.Dispose();
            }

            MessageBodyLoaded = true;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Загружает тело сообщения и возвращает его в виде текста.
        /// </summary>
        /// <returns>Если тело сообщения отсутствует, или оно уже было загружено, то будет возвращена пустая строка.</returns>
        /// <exception cref="System.InvalidOperationException">Вызов метода из ошибочного ответа.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public string ToText()
        {
            #region Проверка состояния

            if (HasError)
            {
                throw new InvalidOperationException(
                    Resources.InvalidOperationException_HttpResponse_HasError);
            }

            #endregion

            if (MessageBodyLoaded)
            {
                return string.Empty;
            }

            var memoryStream = new MemoryStream(
                (ContentLength == -1) ? 0 : ContentLength);

            try
            {
                IEnumerable<BytesWraper> source = GetMessageBodySource();

                foreach (BytesWraper bytes in source)
                {
                    memoryStream.Write(bytes.Value, 0, bytes.Length);
                    _request.ReportBytesReceived(bytes.Length, ContentLength);
                }
            }
            catch (Exception ex)
            {
                HasError = true;

                if (ex is IOException || ex is InvalidOperationException)
                {
                    throw NewHttpException(Resources.HttpException_FailedReceiveMessageBody, ex);
                }

                throw;
            }
            finally
            {
                _receiverHelper = null;
            }

            if (ConnectionClosed())
            {
                _request.Dispose();
            }

            MessageBodyLoaded = true;

            string text = CharacterSet.GetString(
                memoryStream.GetBuffer(), 0, (int)memoryStream.Length);

            return text;
        }
Exemplo n.º 11
0
 public StreamWrapper(Stream baseStream, ReceiverHelper receiverHelper)
 {
     _baseStream = baseStream;
     _receiverHelper = receiverHelper;
 }
Exemplo n.º 12
0
    public List <IBaseMessage> Decode(byte[] buff, int len)
    {
        //拷贝本次的有效字节
        byte[] _b = new byte[len];
        Array.Copy(buff, 0, _b, 0, _b.Length);
        buff = _b;
        if (this._LBuff.Count > 0)
        {
            //拷贝之前遗留的字节
            this._LBuff.AddRange(_b);
            buff = this._LBuff.ToArray();
            this._LBuff.Clear();
        }

        List <IBaseMessage> list = new List <IBaseMessage>();

        using (MemoryStream ms = new MemoryStream(buff))
        {
            using (BinaryReader buffers = new BinaryReader(ms, this.utf8))
            {
                try
                {
                    byte[] _buff;

                    while (true)
                    {
                        #region 包头读取
                        //循环读取包头
                        //判断本次解析的字节是否满足常量字节数
                        if ((buffers.BaseStream.Length - buffers.BaseStream.Position) < ConstLenght)
                        {
                            _buff = buffers.ReadBytes((int)(buffers.BaseStream.Length - buffers.BaseStream.Position));
                            this._LBuff.AddRange(_buff);
                            return(list);
                        }
                        byte tt1 = buffers.ReadByte();
                        byte tt2 = buffers.ReadByte();
                        byte tt3 = buffers.ReadByte();
                        byte tt4 = buffers.ReadByte();
                        if (!(tt1 == t1 && tt3 == t2))
                        {
                            Debug.LogErrorFormat("tt1 = {0},tt2 = {1}", tt1.ToString("x8"), tt2.ToString("x8"));
                            Debug.LogErrorFormat("tt3 = {0},tt4 = {1}", tt3.ToString("x8"), tt4.ToString("x8"));
                            long ttttt = buffers.BaseStream.Seek(-3, SeekOrigin.Current);
                            continue;
                        }
                        else
                        {
                            //Debug.LogErrorFormat("成功 包头!!!");
                        }
                        #endregion

                        #region 包协议
                        int offset = buffers.ReadInt16();
                        //Debug.LogErrorFormat("包协议,长度是 offset={0}",offset);
                        #endregion

                        #region 包解析
                        //剩余字节数大于本次需要读取的字节数
                        if (offset <= (buffers.BaseStream.Length - buffers.BaseStream.Position))
                        {
                            int msgID = buffers.ReadInt32();
                            //Debug.LogErrorFormat("msgID= {0}",msgID);
                            _buff = buffers.ReadBytes(offset - 4);

                            IBaseMessage msg = ReceiverHelper.PopMessage();
                            msg.WriteIn(msgID, _buff, 0, _buff.Length);
                            list.Add(msg);
                            if ((buffers.BaseStream.Length - buffers.BaseStream.Position) > 0)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            //剩余字节数刚好小于本次读取的字节数 存起来,等待接受剩余字节数一起解析
                            _buff = buffers.ReadBytes((int)(buffers.BaseStream.Length - buffers.BaseStream.Position + ConstLenght));
                            this._LBuff.AddRange(_buff);
                        }
                        #endregion

                        break;
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogErrorFormat("MarshalEndian Decode error: {0}", ex);
                }
            }
        }
        return(list);
    }