How to handle HttpClient Keep-Alive response header with max and timeout - c#

HttpClient starts throwing exceptions after a few requests to a specific server. After some tests I noticed that it always stops working at request number 33. The server sends this response header:
Keep-Alive:timeout=5, max=32
I have tried to dispose HttpClient at request number 32 or less but it does not solve the problem.
How should I handle it in order to send requests without problems to this server ?

Try calling HttpClient.Dispose or explicitly setting the Connection: close header
client.DefaultHeaders.Add("Connection", "close");

Related

Owin Self-Hosted WebApi Timeout Settings

I got an Owin self-hosted web-api server, and I'm wondering if I need to change timeout settings when there are huge file downloads?
The client I'm using reads the response withHttpCompletionOption.ResponseHeadersRead.
During debugging, after I stopped for some time in a breakpoint, I got an exception on client side while trying to read from a received stream:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
While debugging I can reproduce this issue. It happens after around 30 seconds waiting in a breakpoint, after the Get-Request to the server returned.
Is this due to some kind of idle timeout, because I hold in a breakpoint and do not work on the received stream? Or can it also happen while I'm reading from the stream when my collection is slow and it takes too long?
Very old question but may help whoever hits the same wall.
I had the same problem with a streaming content and found the initial clue inside HTTPERR folder (C:\Windows\System32\LogFiles\HTTPERR)
2016-08-12 09:17:52 ::1%0 60095 ::1%0 8000 HTTP/1.1 GET
/endpoint/audiostream/0/0/streamer.mp3 - - - Timer_MinBytesPerSecond -
2016-08-12 09:18:19 ::1%0 60118 ::1%0 8000 HTTP/1.1 GET
/endpoint/audiostream/0/0/streamer.mp3 - - - Request_Cancelled -
Owin HttpListener has a TimeOutManager property that allows you to change most timeout/limits. The only way I found to get my webapp HttpListener instance was by accessing its properties
var listener = (OwinHttpListener);
app.Properties["Microsoft.Owin.Host.HttpListener.OwinHttpListener" ]);
listener.Listener.TimeoutManager.MinSendBytesPerSecond = uint.MaxValue;
According to owin codebase, uint.MaxValue as MinSendBytesPerSecond will just disable the flag.

How to send request on one port and response that request on another port in C# windows application

I am using TCPCLient and TcpListenersockets. Here am sending request on port 19000 to 192.168.7.56 IP machine. After giving response from that machine i need to response that i got msg to that machine on port 20000.
Means i want to use one port for all requests and another port for response purpose. Is this possible in C#? Is my scenario correct?
Why this requirement is... In TcpListener socket I am getting continues requests from other machine. So it must be always available to get those requests....
After getting request on TcpListener I need to response them that I got req like aknowledgement on different port.
Please suggest how to implement this scenario?
Thanks,
Syed Chand Basha
well the common pattern is
one port and behind a pool for processing request (here you can verify the load the server or maximum clients for processing..etc)
when request enter the pool will create an new thread for process that request
while the main pool can still listening request
also exist other thread monitor the threads for timeout or errors so it can kill process for errors or timeout o long processing
regards

HttpWebRequest, Keep-Alive as Fiddler does?

Using HttpWebRequest, I'm trying to query a secured (negotiate) url behind a load balancing setup in round-robin mode (two IIS 7.5 servers). Seems simple enough, but I have some problems.
The first anonymous request goes on one server and the negotiate part goes on the other. The problem is that it takes about six seconds between these two requests, so it is way too long. Trying to diagnose the delay, I realized that, going through Fiddler's proxy, all the requests went on the same server, so it took less than one second total. If I disable Fiddlers option "reuse server connections", then my requests have the same behavior as without Fiddler and it takes forever.
Googling this, I ended up on this link: http://fiddler2.com/blog/blog/2013/02/28/help!-running-fiddler-fixes-my-app-
I know that Fiddler is using sockets and its own connection pool, but is there a way to reproduce the same behavior using .NET HttpWebRequest so that my requests (anonymous and negotiate) will reuse connections and end up on the same server?
Here is a quick test that takes about 70 seconds to complete without Fiddler, and about 2 seconds going through Fiddler...
Also, please note that it isn't a Proxy detection delay and that sticky session are disabled on the nlb.
public void Main(string[] args)
{
int i = 0;
while (i < 10)
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://nlb/service.asmx");
HttpWebResponse response;
wr.KeepAlive = true;
wr.UseDefaultCredentials = true;
response = (HttpWebResponse)wr.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
response.Close();
i++;
}
}
This is another proof that Fiddler is plain awesome!
Thanks for any advice.
Just a shot here, and maybe it seems too easy -
But the last line of your code is Response.Close(). The documentation prior to .NET 4.5 doesn't say much about this other than it "closes the existing socket connection."
In .NET 4.5 however, this is the documentation:
This method terminates the connection to the client in an abrupt
manner and is not intended for normal HTTP request processing.
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.close(v=vs.110).aspx
I'll admit that I don't know some of the subtle differences between .NET 4.5 and the prior versions of HttpResponse; however, I do think that logically, Connection.Close() is not compatible with Keep-Alive; and you could be seeing the behavior of Fiddler intervening (maybe as a bug) to patch over this. Just a theory- needs testing.

Closing connection to browser early and returning respond status

I am implementing a custom IHttpModule in a project, which filter file uploading and provide upload status.
I want the custom module to close the connection early (don't want to receive all the data the other side send, which is allowed to be big, save the incoming bandwidth).
Is it a possibility using HTTP protocol?
I tried sending "ContentLength: 0" and "Connection: close" header, flush the response, close the connection (HttpWorkerRequest.CloseConnection).
workerRequest.SendStatus(400, "Bad request");
workerRequest.SendKnownResponseHeader(HttpWorkerRequest.HeaderContentLength, "0");
workerRequest.SendKnownResponseHeader(HttpWorkerRequest.HeaderConnection, "close");
workerRequest.FlushResponse(false);
workerRequest.CloseConnection();
((HttpApplication)sender).CompleteRequest();
The browser/firefox response is displaying the "Connection reset" error message.
Without any sign of receiving any data/header/status from the server.
Thanks in advance.
An http client expects response only after it has completed sending the data. You should modify the client to make multiple requests of small sizes so a response can be sent to it instead of having server close the connection (which will not work and isn't working as you've tested already).
Check the http handler implemented in http://slfileupload.codeplex.com/ for a sample of how it is typically done.

Avoiding 504 on remote server .NET

I am using HttpWebRequest to download a remote file, however i get a 504 error.
I pasted the url in firefox and the first and 3rd try it took 16seconds, the 2nd nothing happened (it looked like it timed out).
How do i decrease the 504 error? Would changing HttpWebRequest timeout help? should i attempt to retry the file (lets say 3 times) if i receive a 504 error?
That's a server problem. There's no way for you to prevent that. I would retry a couple of times adding some Thread.Sleep in between.
5xx is a server error. Look at the entity body of the response to see if the server gives any hint as to why this is happening.
You can get the entity body by getting the Response from the WebException object.
Try putting an & at the end of your POST request body:
variable=value&
Maybe the server is waiting for POST data.

Categories

Resources