I have a simple webclient which simply sends POST messages to server and get the responses. I set KeepAlive=true
by overriding GetWebRequest(...)' of System.Net.WebClient)' to use persistent connections.
And the server to which my client talks to have a limit on the number of connections I can open (to avoid DoS attacks, I guess!). My client simply executes bunch of queries against this server in parallel - so to limit the number of requests I make against the server I used a semaphore (please see code snippet) - i.e. to ensure I didn't cross the connection limit at any given time.
However on a specific customer's environment, the server is actively denying requests by saying 'the connection limit has been reached'.
My questions:
How do I know at any given instant, how many connections my client is opening against the server? I am using Fiddler - but not too sure whether this info is available?
Since I am limiting the number of requests I make using semaphore (in this example 75), assuming there are no connections opened by other clients or apps from the customer's box to server, is there a possibility the .net opening more than '75' persistent connections since I set the 'keep alive' to true. My guess is since at most there are only 75 requests, the connections shouldn't be more than 75, and all the further requests simply reuse the existing connections. But, since I can't see - I can't confirm I guess.
Limiting number of concurrent requests by using semaphore:
Semaphore semaphore = new Semaphore(initialCount:75, maximumCount:75);
try
{
//at any given time do not send more than 75 requests to server
semaphore.WaitOne();
using (var myWebClient = new MyWebClient(timeoutSeconds: 300, useragent: "dreamer"))
{
byte[] responseBytes = myWebClient.UploadData("http://myserverurl",
UTF8Encoding.UTF8.GetBytes("inputMessageRequest"));
}
}
finally
{
semaphore.Release();
}
My Web Client (setting keep alive to true by overriding GetWebRequest):
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.UserAgent = this.UserAgent;
request.KeepAlive = true;
request.Timeout = this.TimeoutSeconds;
request.PreAuthenticate = true;
return request;
}
public int TimeoutSeconds { get; set; }
public string UserAgent { get; set; }
public MyWebClient(int timeoutSeconds, string useragent)
{
this.TimeoutSeconds = timeoutSeconds;
this.UserAgent = useragent;
}
}