|
10 | 10 | using System.IO; |
11 | 11 | using System.Text.RegularExpressions; |
12 | 12 | using System.Threading.Tasks; |
| 13 | +using System.Threading; |
| 14 | +using System.Net.Http; |
13 | 15 |
|
14 | 16 | namespace Microsoft.AspNetCore.SpaServices.AngularCli |
15 | 17 | { |
@@ -89,13 +91,48 @@ private static async Task<AngularCliServerInfo> StartAngularCliServerAsync( |
89 | 91 | var serverInfo = new AngularCliServerInfo { Port = uri.Port }; |
90 | 92 |
|
91 | 93 | // Even after the Angular CLI claims to be listening for requests, there's a short |
92 | | - // period where it will give an error if you make a request too quickly. Give it |
93 | | - // a moment to finish starting up. |
94 | | - await Task.Delay(500); |
| 94 | + // period where it will give an error if you make a request too quickly |
| 95 | + await WaitForAngularCliServerToAcceptRequests(uri); |
95 | 96 |
|
96 | 97 | return serverInfo; |
97 | 98 | } |
98 | 99 |
|
| 100 | + private static async Task WaitForAngularCliServerToAcceptRequests(Uri cliServerUri) |
| 101 | + { |
| 102 | + // To determine when it's actually ready, try making HEAD requests to '/'. If it |
| 103 | + // produces any HTTP response (even if it's 404) then it's ready. If it rejects the |
| 104 | + // connection then it's not ready. |
| 105 | + const int MaxAttempts = 10; |
| 106 | + const int SecondsBetweenAttempts = 1; |
| 107 | + |
| 108 | + var attemptsMade = 0; |
| 109 | + var client = new HttpClient(); |
| 110 | + |
| 111 | + while (true) |
| 112 | + { |
| 113 | + try |
| 114 | + { |
| 115 | + // If we get any HTTP response, the CLI server is ready |
| 116 | + await client.SendAsync( |
| 117 | + new HttpRequestMessage(HttpMethod.Head, cliServerUri), |
| 118 | + new CancellationTokenSource(1000).Token); |
| 119 | + return; |
| 120 | + } |
| 121 | + catch (Exception ex) |
| 122 | + { |
| 123 | + attemptsMade++; |
| 124 | + if (attemptsMade >= MaxAttempts) |
| 125 | + { |
| 126 | + throw new InvalidOperationException( |
| 127 | + "Timed out waiting for the @angular/cli server to accept HTTP requests. " + |
| 128 | + "See inner exception for details.", ex); |
| 129 | + } |
| 130 | + |
| 131 | + Thread.Sleep(SecondsBetweenAttempts * 1000); |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
99 | 136 | class AngularCliServerInfo |
100 | 137 | { |
101 | 138 | public int Port { get; set; } |
|
0 commit comments