Skip to content

sockets end in close_wait state after some time #29

Description

@GopinathSadasivam

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);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions