I wrote a C# program which post HTTP heartbeat request every 5 second,it runs well at the beginning,but after about 20-40 mins, it keeps throwing webException at the method HttpWebRequest.BeginGetRequestStream( ) ( or at HttpWebResponse.EndGetResponse() if I don't need to post data).
I met this problem in some specific computers, whose performance wasn't that good.
I've made several attempts,but still get the same result:
- change another server address
- use socket to post http request, and get socketException when new a socket(before socket.connect())
- asynchronous and synchronous http request
- use .net 4.0 (I use .net3.5 currently)
- almost the same code in winForm and WPF program
- make sure do nothing with proxy or firewall
here is the exception stacktrace:
System.Net.WebException: the underlying connection was closed:unable to connect to the remote server.
---> System.Net.Sockets.SocketException: an invalid argument was supplied.
at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
at System.Net.Connection.CompleteStartConnection(Boolean async, HttpWebRequest httpWebRequest)
here is the kernal part of my code:
public MainWindow()
{
InitializeComponent();
timer = new Timer(new TimerCallback(delegate (object obj)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.KeepAlive = false;
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, 15000, true);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}), null, Timeout.Infinite, Timeout.Infinite);
}
private void TimeoutCallback(object state, bool timeout)
{
if (timeout)
{
HttpWebRequest request = state as HttpWebRequest;
if (request != null)
{
request.Abort();
}
}
}
private void ResponseCallback(IAsyncResult result)
{
try
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();
responseStream.Close();
reader.Close();
response.Close();
Console.WriteLine(responseString);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I don't think there is anything wrong with the code, maybe is the .net problem or network problem, I am very grateful if someone give me some advices.