2017-04-20 64 views
0

我正在編寫C#客戶端REST服務來訪問Http流API。我應該打開流,並接收由無盡流的服務器發送的消息。從流中讀取的外部命令應停止。 HttpClient用於實現。變量streamingActive用於停止從流中讀取,因爲reader.EndOfStream永遠不會返回值true。在無盡的Http流超時

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秒通話reader.EndOfStream拋出異常「的操作已超時。」

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

有什麼辦法讓流開(假設)到永遠嗎?

回答

0

如果您願意放棄StreamReader,爲什麼不直接打開Stream對象?下面是一個通用的應用程序(使用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。如果您仍然需要取消操作,您可以使用TaskCancellationToken方法。