Bug 5710 - HttpWebRequest::Abort does not release socket
Summary: HttpWebRequest::Abort does not release socket
Status: RESOLVED FIXED
Alias: None
Product: Class Libraries
Classification: Mono
Component: System ()
Version: master
Hardware: PC Linux
: Highest normal
Target Milestone: Untriaged
Assignee: Gonzalo Paniagua Javier
URL:
Depends on:
Blocks:
 
Reported: 2012-06-18 13:17 UTC by Marek Safar
Modified: 2012-06-18 22:53 UTC (History)
2 users (show)

Tags:
Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
RESOLVED FIXED

Description Marek Safar 2012-06-18 13:17:28 UTC
Test app extracted from unit test

Running on mono produces

~X.~X
Unhandled Exception: System.Net.WebException: The request timed out

Works on .net


using System.IO;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Globalization;

class C
{
	public static void Main ()
	{
		while (true) {
			IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8001);
			string url = "http://" + ep.ToString () + "/test/";

			using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
				responder.Start ();

				HttpWebRequest req;

				req = (HttpWebRequest)WebRequest.Create (url);
				req.Timeout = 5000;
				req.Method = "POST";
				req.SendChunked = false;
				req.KeepAlive = false;
				req.AllowWriteStreamBuffering = false;
				req.BeginGetResponse (null, null);
				req.Abort ();

				Console.Write ("~");

				req = (HttpWebRequest)WebRequest.Create (url);
				req.Timeout = 5000;
				req.Method = "POST";
				req.SendChunked = true;
				req.KeepAlive = false;
				req.AllowWriteStreamBuffering = false;

				Console.Write ("X");

				var r = req.GetRequestStream ();
				r.WriteByte (1);
				req.BeginGetResponse (null, null);

				req.Abort (); // REMOVING THIS CALL FIXES THE TIMEOUT

				Console.Write (".");
			}
		}
	}

	internal static byte [] EchoRequestHandler (Socket socket)
	{
		MemoryStream ms = new MemoryStream ();
		byte [] buffer = new byte [4096];
		int bytesReceived = socket.Receive (buffer);
		while (bytesReceived > 0) {
			ms.Write (buffer, 0, bytesReceived);
			// We don't check for Content-Length or anything else here, so we give the client a little time to write
			// after sending the headers
			Thread.Sleep (200);
			if (socket.Available > 0) {
				bytesReceived = socket.Receive (buffer);
			} else {
				bytesReceived = 0;
			}
		}
		ms.Flush ();
		ms.Position = 0;
		StreamReader sr = new StreamReader (ms, Encoding.UTF8);
		string request = sr.ReadToEnd ();

		StringWriter sw = new StringWriter ();
		sw.WriteLine ("HTTP/1.1 200 OK");
		sw.WriteLine ("Content-Type: text/xml");
		sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
		sw.WriteLine ();
		sw.Write (request);
		sw.Flush ();

		return Encoding.UTF8.GetBytes (sw.ToString ());
	}

}

public delegate byte[] SocketRequestHandler (Socket socket);

public class SocketResponder : IDisposable
{
	private TcpListener tcpListener;
	private readonly IPEndPoint _localEndPoint;
	private Thread listenThread;
	private SocketRequestHandler _requestHandler;
	private bool _stopped = true;
	private readonly object _syncRoot = new object ();
	private const int SOCKET_CLOSED = 10004;
	private const int SOCKET_INVALID_ARGS = 10022;

	public SocketResponder (IPEndPoint localEP, SocketRequestHandler requestHandler)
	{
		_localEndPoint = localEP;
		_requestHandler = requestHandler;
	}

	public IPEndPoint LocalEndPoint {
		get { return _localEndPoint; }
	}

	public void Dispose ()
	{
		Stop ();
	}

	public bool IsStopped {
		get {
			lock (_syncRoot) {
				return _stopped;
			}
		}
	}

	public void Start ()
	{
		lock (_syncRoot) {
			if (!_stopped)
				return;
			_stopped = false;
			tcpListener = new TcpListener (LocalEndPoint);
			tcpListener.Start ();
			listenThread = new Thread (new ThreadStart (Listen));
			listenThread.Start ();
		}
	}

	public void Stop ()
	{
		lock (_syncRoot) {
			if (_stopped)
				return;
			_stopped = true;
			if (tcpListener != null) {
				tcpListener.Stop ();
				tcpListener = null;
				Thread.Sleep (50);
			}
		}
	}

	private void Listen ()
	{
		while (!_stopped) {
			Socket socket = null;
			try {
				socket = tcpListener.AcceptSocket ();
				socket.Send (_requestHandler (socket));
				try {
					socket.Shutdown (SocketShutdown.Receive);
					socket.Shutdown (SocketShutdown.Send);
				} catch {
				}
			} catch (SocketException ex) {
				Console.WriteLine (ex);
				// ignore interruption of blocking call
				//if (ex.ErrorCode != SOCKET_CLOSED && ex.ErrorCode != SOCKET_INVALID_ARGS)
				//	throw;
			} finally {
				//Thread.Sleep (500);
				if (socket != null)
					socket.Close ();
			}
		}
	}
}
Comment 1 Gonzalo Paniagua Javier 2012-06-18 22:45:30 UTC
I think I have a fix for this. I'll do some more testing before pushing it.
Comment 2 Gonzalo Paniagua Javier 2012-06-18 22:53:28 UTC
Fixed in master/271524d and mono-2-10/5c5be86