无尽的HTTP流



我正在编写c#client以访问http流api。我本来应该打开流并接收服务器在无尽流中发送的消息。在外部命令上,从流读数应停止。HTTPClient用于实现。由于读取器,可变流载体用于停止从流读取。

using (HttpClient httpClient = new HttpClient())
{
    httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
    var messagesUri = "http://127.0.0.1:8080/api/messages/progress?sender_id=7837492342";
    var stream = httpClient.GetStreamAsync(messagesUri).Result;
    using (var reader = new StreamReader(stream))
    {
        while (streamingActive && !reader.EndOfStream)
        {
            var currentLine = reader.ReadLine();
            try
            {
                var psMessage = JsonConvert.DeserializeObject<PSMessage>(currentLine);
                Console.WriteLine(psMessage);
            }
            catch (JsonReaderException exc)
            {}
        }
    }
}

在服务器传来消息时,它可以正常工作。如果服务器中没有新消息,则〜300 s呼叫读取器。

at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Http.HttpClientHandler.WebExceptionWrapperStream.Read(Byte[] buffer, Int32 offset, Int32 count)

有什么办法可以永远(假设(永远开放?

如果您愿意放开流读器,为什么不直接打开流对象呢?以下是通用应用程序(使用Windows.web API(

HttpResponseMessage respMessage;
//note: client and request is defined elsewhere.
respMessage = client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);
using (var responseStream = await respMessage.Content.ReadAsInputStreamAsync())
{
   using (var fileWriteStream = await fileToStore.OpenAsync(FileAccessMode.ReadWrite))
     {
        while (streamingActive && (await responseStream.ReadAsync(streamReadBuffer, bufferLength, InputStreamOptions.None)).Length > 0)
        {
          await fileWriteStream.WriteAsync(streamReadBuffer);
       }
     }
}

这应该无限期地等待await responseStream.ReadAsync。如果您仍然需要取消操作经验,则可以使用CancellationToken方法使用Task

相关内容

  • 没有找到相关文章

最新更新