Friday, February 13, 2009

The underlying connection was closed: A connection that was expected to be kept alive was closed by the server

Well the bad news is that this worked for some time but then started to not work again. Looks like i am back to the drawing board.


Ok it took me 2 days to track this down but I think I have solved it.

I have 2 different .net 2.0 libraries in the same application that both access the same third-party Java web service. Oh by the way this worked no problem in .net 1.0

Well this was throwing an System.Net.WebException "The underlying connection was closed:" randomly.

InnerException: System.IO.IOException
Message="Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
Source="System"
StackTrace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
InnerException: System.Net.Sockets.SocketException
Message="An existing connection was forcibly closed by the remote host"
Source="System"
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)


I spent forever searching the net looking for a solution to this, with little to no success.
Well I finally came across this link. To resolve this problem you need to disable the keep-alive feature.

In the .NET Framework, you need to set the HttpWebRequest.KeepAlive property to FALSE.
To do this I created a web service reference then modified the generated Reference.cs class and added

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);
webRequest.KeepAlive = false;
return webRequest;
}

now I know this will probably add a little over-head to my application but so what it solved my devastating error :-)

No comments: