From b66620c9da0dce92acb081d3d362d64e38508d24 Mon Sep 17 00:00:00 2001 From: Lucas Bortoli Date: Mon, 27 Jun 2022 08:26:11 -0300 Subject: [PATCH] Set HttpClient timeout to infinite --- ntfysh_client/NotificationListener.cs | 60 +++++++++++++++------------ 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/ntfysh_client/NotificationListener.cs b/ntfysh_client/NotificationListener.cs index 7a6258c..75f6118 100644 --- a/ntfysh_client/NotificationListener.cs +++ b/ntfysh_client/NotificationListener.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Net; using System.Net.Http; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Web; @@ -28,46 +29,53 @@ namespace ntfysh_client httpClient = new HttpClient(); subscribedTopics = new Dictionary(); + httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite); ServicePointManager.DefaultConnectionLimit = 100; } public async Task SubscribeToTopic(string topicId) { - var stream = await httpClient.GetStreamAsync($"https://ntfy.sh/{HttpUtility.UrlEncode(topicId)}/json"); - - using (StreamReader reader = new StreamReader(stream)) + HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, $"https://ntfy.sh/{HttpUtility.UrlEncode(topicId)}/json"); + using (var response = await httpClient.SendAsync(msg, HttpCompletionOption.ResponseHeadersRead)) { - subscribedTopics.Add(topicId, reader); - - try + using (var body = await response.Content.ReadAsStreamAsync()) { - // The loop will be broken when this stream is closed - while (true) + using (StreamReader reader = new StreamReader(body)) { - var line = await reader.ReadLineAsync(); + subscribedTopics.Add(topicId, reader); - Debug.WriteLine(line); - - NtfyEventObject nev = JsonConvert.DeserializeObject(line); - - if (nev.Event == "message") + try { - if (OnNotificationReceive != null) + // The loop will be broken when this stream is closed + while (true) { - var evArgs = new NotificationReceiveEventArgs(nev.Title, nev.Message); - OnNotificationReceive(this, evArgs); + var line = await reader.ReadLineAsync(); + + Debug.WriteLine(line); + + NtfyEventObject nev = JsonConvert.DeserializeObject(line); + + if (nev.Event == "message") + { + if (OnNotificationReceive != null) + { + var evArgs = new NotificationReceiveEventArgs(nev.Title, nev.Message); + OnNotificationReceive(this, evArgs); + } + } } } - } - } catch(Exception ex) - { - Debug.WriteLine(ex); + catch (Exception ex) + { + Debug.WriteLine(ex); - // If the topic is still registered, then that stream wasn't mean to be closed (maybe network failure?) - // Restart it - if (subscribedTopics.ContainsKey(topicId)) - { - SubscribeToTopic(topicId); + // If the topic is still registered, then that stream wasn't mean to be closed (maybe network failure?) + // Restart it + if (subscribedTopics.ContainsKey(topicId)) + { + SubscribeToTopic(topicId); + } + } } } }