uhttpsharp icon indicating copy to clipboard operation
uhttpsharp copied to clipboard

sockets end in close_wait state after some time

Open GopinathSadasivam opened this issue 5 years ago • 1 comments

Looks like we are missing a time-out on stream reader in uhttpsharp\HttpClient.cs

When remote http client gets disconnected due to some network issues (or because of proxies in between not handling the keep-alive header properly), uHttpSharp library code fails to close the socket, this results in open sockets stuck in close_wait state. Am new to C# not sure how to add this time out.

 {
        try
        {
            await InitializeStream();

            while (_client.Connected)
            {
                // TODO : Configuration.
                var limitedStream = new NotFlushingStream(new LimitedStream(_stream));

                var request = await _requestProvider.Provide(new MyStreamReader(limitedStream)).ConfigureAwait(false);

                if (request != null)
                {
                    UpdateLastOperationTime();

                    var context = new HttpContext(request, _client.RemoteEndPoint);

                    Logger.InfoFormat("{1} : Got request {0}", request.Uri, _client.RemoteEndPoint);


                    await _requestHandler(context).ConfigureAwait(false);

                    if (context.Response != null)
                    {
                        var streamWriter = new StreamWriter(limitedStream) { AutoFlush = false };
                        streamWriter.NewLine = "\r\n";
                        await WriteResponse(context, streamWriter).ConfigureAwait(false);

                         //v----- connections seem to be stuck here, resulting in piling up of  sockets in close_wait state
                        await limitedStream.ExplicitFlushAsync().ConfigureAwait(false); 

                        if (!request.Headers.KeepAliveConnection() || context.Response.CloseConnection)
                        {
                            _client.Close();
                        }
                    }

                    UpdateLastOperationTime();
                }
                else
                {
                    _client.Close();
                }
            }
        }
        catch (Exception e)
        {
            // Hate people who make bad calls.
            Logger.WarnException(string.Format("Error while serving : {0}", _remoteEndPoint), e);
            _client.Close();
        }

        Logger.InfoFormat("Lost Client {0}", _remoteEndPoint);
    }

GopinathSadasivam avatar Jun 07 '19 04:06 GopinathSadasivam

Hi I have the same problem with sockets end in close_wait state in other projects, Did you find solution for this one in this project ?

fbaghdadlian-b avatar Sep 18 '22 12:09 fbaghdadlian-b