Created
December 16, 2014 13:42
-
-
Save ludo6577/a36878bb770ca1f652aa to your computer and use it in GitHub Desktop.
Send a HTTPWebRequest with a timeout on the connection (http://stackoverflow.com/questions/26962615/how-can-i-specify-a-connection-only-timeout-when-executing-web-requests/27067206#27067206)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static WebRequest request; | |
private static void sendAndReceive() | |
{ | |
// The request with a big timeout for receiving large amout of data | |
request = HttpWebRequest.Create("http://localhost:8081/index/"); | |
request.Timeout = 100000; | |
// The connection timeout | |
var ConnectionTimeoutTime = 100; | |
Timer timer = new Timer(ConnectionTimeoutTime); | |
timer.Elapsed += connectionTimeout; | |
timer.Enabled = true; | |
Console.WriteLine("Connecting..."); | |
try | |
{ | |
using (var stream = request.GetRequestStream()) | |
{ | |
Console.WriteLine("Connection success !"); | |
timer.Enabled = false; | |
/* | |
* Sending data ... | |
*/ | |
System.Threading.Thread.Sleep(1000000); | |
} | |
using (var response = (HttpWebResponse)request.GetResponse()) | |
{ | |
/* | |
* Receiving datas... | |
*/ | |
} | |
} | |
catch (WebException e) | |
{ | |
if(e.Status==WebExceptionStatus.RequestCanceled) | |
Console.WriteLine("Connection canceled (timeout)"); | |
else if(e.Status==WebExceptionStatus.ConnectFailure) | |
Console.WriteLine("Can't connect to server"); | |
else if(e.Status==WebExceptionStatus.Timeout) | |
Console.WriteLine("Timeout"); | |
else | |
Console.WriteLine("Error"); | |
} | |
} | |
static void connectionTimeout(object sender, System.Timers.ElapsedEventArgs e) | |
{ | |
Console.WriteLine("Connection failed..."); | |
Timer timer = (Timer)sender; | |
timer.Enabled = false; | |
request.Abort(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment