Exemple #1
0
        protected override object Invoke(MethodInfo targetMethod, object[] args)
        {
            ClientActionHanler handler = Cluster.GetHandler((MethodInfo)targetMethod);
            var rinfo = handler.GetRequestInfo(args);

            if (handler.NodeAgent == null || handler.NodeAgent.Version != Cluster.Version)
            {
                handler.NodeAgent = Cluster.GetAgent(rinfo.Url);
            }
            HttpHost host = handler.NodeAgent.Node.GetClient();

            if (host == null)
            {
                Exception error = new HttpClientException(null, null, $"request {rinfo.Url} no http nodes are available");
                if (handler.Async)
                {
                    //Type gtype = typeof(AnyCompletionSource<>);
                    //Type type = gtype.MakeGenericType(handler.ReturnType);
                    IAnyCompletionSource source = CompletionSourceFactory.Create(handler.ReturnType, Cluster.TimeOut);  //(IAnyCompletionSource)Activator.CreateInstance(type);
                    source.Error(error);
                    return(source.GetTask());
                }
                else
                {
                    throw error;
                }
            }
            if (!handler.Async)
            {
                throw new Exception($"{rinfo.Method} method is not supported and the return value must be task!");
            }
            else
            {
                var request = rinfo.GetRequest(host);
                foreach (var item in Header)
                {
                    request.Header[item.Key] = item.Value;
                }
                var task = request.Execute();
                IAnyCompletionSource source = CompletionSourceFactory.Create(handler.ReturnType, Cluster.TimeOut);
                source.Wait <Response>(task, (c, t) =>
                {
                    if (t.Result.Exception != null)
                    {
                        c.Error(t.Result.Exception);
                    }
                    else
                    {
                        c.Success(t.Result.Body);
                    }
                });
                return(source.GetTask());
            }
        }
Exemple #2
0
        private async void OnExecute()
        {
            HttpClientHandler client = null;
            Response          response;
            bool closeClient = false;

            try
            {
                object result = null;
                requestResult = new TaskCompletionSource <object>();
                client        = await HttpHost.Pool.Pop();

                Client = client.Client;
                AsyncTcpClient asyncClient = (AsyncTcpClient)client.Client;
                asyncClient.ClientError   = onEventClientError;
                asyncClient.PacketReceive = OnEventClientPacketCompleted;
                GetConnection?.Invoke(asyncClient);
#if NETCOREAPP2_1
                using (CodeTrackFactory.Track(Url, CodeTrackLevel.Function, mRequestTrack?.Activity?.Id, "HTTPClient", "Protocol", "Write"))
                {
                    asyncClient.Send(this);
                    Status = RequestStatus.SendCompleted;
                }
#else
                asyncClient.Send(this);
                Status = RequestStatus.SendCompleted;
#endif

#if NETCOREAPP2_1
                using (CodeTrackFactory.Track(Url, CodeTrackLevel.Function, mRequestTrack?.Activity?.Id, "HTTPClient", "Protocol", "Read"))
                {
                    var a = requestResult.Task;
                    result = await a;
                }
#else
                var a = requestResult.Task;
                result = await a;
#endif
                if (result is Exception error)
                {
                    response           = new Response();
                    response.Exception = new HttpClientException(this, HttpHost.Uri, error.Message, error);
                    Status             = RequestStatus.Error;
                    closeClient        = true;
                }
                else
                {
                    response = (Response)result;
                    Status   = RequestStatus.Received;
                }

                if (response.Exception == null)
                {
                    int code = int.Parse(response.Code);
                    if (response.Length > 0)
                    {
                        try
                        {
                            if (code >= 200 && code < 300)
                            {
                                response.Body = this.Formater.Deserialization(response, response.Stream, this.BodyType, response.Length);
                            }
                            else
                            {
                                response.Body = response.Stream.ReadString(response.Length);
                            }
                        }
                        finally
                        {
                            response.Stream.ReadFree(response.Length);
                            if (response.Chunked)
                            {
                                response.Stream.Dispose();
                            }
                            response.Stream = null;
                        }
                    }
                    if (!response.KeepAlive)
                    {
                        client.Client.DisConnect();
                    }
                    if (code >= 400)
                    {
                        response.Exception      = new HttpClientException(this, HttpHost.Uri, $"{Url}({response.Code}) [{response.Body}]");
                        response.Exception.Code = code;
                    }
                    Status = RequestStatus.Completed;
                }
            }
            catch (Exception e_)
            {
                HttpClientException clientException = new HttpClientException(this, HttpHost.Uri, e_.Message, e_);
                response = new Response {
                    Exception = clientException
                };
                Status      = RequestStatus.Error;
                closeClient = true;
            }
            if (response.Exception != null)
            {
                HttpHost.AddError(response.Exception.SocketError);
            }
            else
            {
                HttpHost.AddSuccess();
            }
            Response.Current = response;
            this.Response    = response;
            if (client != null)
            {
                if (client.Client is AsyncTcpClient asclient)
                {
                    asclient.ClientError   = null;
                    asclient.PacketReceive = null;
                }
                if (closeClient)
                {
                    await DisConnect(client.Client);
                }
                HttpHost.Pool.Push(client);
                client = null;
            }
            await Task.Run(() => mTaskCompletionSource.Success(response));
        }
Exemple #3
0
        private async void OnExecute()
        {
            HttpClient client = null;
            Response   response;

            try
            {
                client = HttpHost.Pool.Pop();
                client.RequestCommpletionSource = mTaskCompletionSource;
                Client = client.Client;
                if (client.Client is AsyncTcpClient)
                {
                    AsyncTcpClient asyncClient = (AsyncTcpClient)client.Client;
                    GetConnection?.Invoke(asyncClient);
                    var a = asyncClient.ReceiveMessage();
                    if (!a.IsCompleted)
                    {
                        asyncClient.Send(this);
                        Status = RequestStatus.SendCompleted;
                    }
                    var result = await a;
                    if (result is Exception error)
                    {
                        response           = new Response();
                        response.Exception = new HttpClientException(this, HttpHost.Uri, error.Message, error);
                        Status             = RequestStatus.Error;
                    }
                    else
                    {
                        response = (Response)result;
                        Status   = RequestStatus.Received;
                    }
                }
                else
                {
                    TcpClient syncClient = (TcpClient)client.Client;
                    syncClient.SendMessage(this);
                    Status   = RequestStatus.SendCompleted;
                    response = syncClient.ReceiveMessage <Response>();
                    Status   = RequestStatus.Received;
                }
                if (response.Exception == null)
                {
                    int code = int.Parse(response.Code);
                    if (response.Length > 0)
                    {
                        try
                        {
                            if (code == 200)
                            {
                                response.Body = this.Formater.Deserialization(response, response.Stream, this.BodyType, response.Length);
                            }
                            else
                            {
                                response.Body = response.Stream.ReadString(response.Length);
                            }
                        }
                        finally
                        {
                            response.Stream.ReadFree(response.Length);
                            if (response.Chunked)
                            {
                                response.Stream.Dispose();
                            }
                            response.Stream = null;
                        }
                    }
                    if (!response.KeepAlive)
                    {
                        client.Client.DisConnect();
                    }
                    if (code != 200)
                    {
                        response.Exception      = new HttpClientException(this, HttpHost.Uri, $"{Url}({response.Code}) [{response.Body}]");
                        response.Exception.Code = code;
                    }
                    Status = RequestStatus.Completed;
                }
            }
            catch (Exception e_)
            {
                HttpClientException clientException = new HttpClientException(this, HttpHost.Uri, e_.Message, e_);
                response = new Response {
                    Exception = clientException
                };
                Status = RequestStatus.Error;
            }
            if (response.Exception != null)
            {
                HttpHost.AddError(response.Exception.SocketError);
            }
            else
            {
                HttpHost.AddSuccess();
            }
            Response.Current = response;
            this.Response    = response;
            if (client != null)
            {
                HttpHost.Pool.Push(client);
            }
            Task.Run(() => mTaskCompletionSource.Success(response));
        }