如何使用带有Firebase REST Streaming API的.NET HttpClient关闭Firebase服务器上的EventSource连接

时间:2015-06-09 22:23:28

标签: .net c#-4.0 firebase server-sent-events rest-firebase

我正在使用.NET HttpClient来实现Firebase Streaming Rest API,它本身支持EventSource / Server-Sent Events协议。

此API的文档位于:https://www.firebase.com/docs/rest/api/#section-streaming

下面显示的实现可以正常连接到Firebase并获取我的数据,在Windows服务中运行,自动更新其业务逻辑,然后每隔10分钟将 GetAndProcessFirebaseHttpResponse 作为新任务调用。< / p>

问题是,当我查看我的Firebase仪表板时,每次任务运行时,并发连接数会增加1,而我似乎无法告诉Firebase应该在Firebase端关闭连接而不再进一步关闭发送的数据。

以下是我在示例应用中添加的代码的简化示例。每当我调用GetAndProcessFirebaseHttpResponse时,我的Firebase仪表板上的另一个并发连接递增,即使我取消任务后该连接仍然存在(通过CancellationSourceToken.Token.ThrowIfCancellationRequested()):

    public void GetAndProcessFirebaseHttpResponse(CancellationTokenSource cancellationTokenSource)
    {
        HttpResponseMessage httpResponse = ListenAsync().Result;

        using (httpResponse)
        {
            using (Stream contentStream = httpResponse.Content.ReadAsStreamAsync().Result)
            {
                using (StreamReader contentStreamReader = new StreamReader(contentStream))
                {
                    while (true)
                    {
                        if (cancellationTokenSource.IsCancellationRequested)
                        {
                            httpResponse.RequestMessage.Dispose();
                        }

                        cancellationTokenSource.Token.ThrowIfCancellationRequested();

                        string read = contentStreamReader.ReadLineAsync().Result;

                        // Process the data here
                    }
                }
            }
        }
    }

    private async Task<HttpResponseMessage> ListenAsync()
    {
        // Create HTTP Client which will allow auto redirect as required by Firebase
        HttpClientHandler httpClientHandler = new HttpClientHandler();
        httpClientHandler.AllowAutoRedirect = true;

        HttpClient httpClient = new HttpClient(httpClientHandler, true);
        httpClient.BaseAddress = new Uri(_firebasePath);
        httpClient.Timeout = TimeSpan.FromSeconds(60);

        string requestUrl = _firebasePath + ".json?auth=" + _authSecret;
        Uri requestUri = new Uri(requestUrl);

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));

        HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
        response.EnsureSuccessStatusCode();

        return response;
    }

HttpResponseMessage,Stream,StreamReader,HttpRequestMessage都被处理掉了。 HttpClient不是,因为建议它不需要(参见Do HttpClient and HttpClientHandler have to be disposed?)。这些处理自然会释放客户端上的资源,但我猜他们没有与 Firebase服务器进行任何通信,无法在Firebase端关闭连接。

我的问题是:将.NET HttpClient与Firebase REST Streaming API一起使用,如何与Firebase REST端点进行通信,我已完成连接并且应该在Firebase端关闭它?

0 个答案:

没有答案