Skip to content

Commit 2e633f9

Browse files
authored
Improvements in stability and restart (#41)
***NO_CI***
1 parent cbeb33e commit 2e633f9

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

nanoFramework.WebServer/WebServer.cs

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,6 @@ public WebServer(int port, HttpProtocol protocol, Type[] controllers)
246246
Port = port;
247247
string prefix = Protocol == HttpProtocol.Http ? "http" : "https";
248248
_listener = new HttpListener(prefix, port);
249-
_serverThread = new Thread(StartListener);
250249
Debug.WriteLine("Web server started on port " + port.ToString());
251250
}
252251

@@ -346,6 +345,11 @@ private Authentication ExtractAuthentication(string strAuth)
346345
/// </summary>
347346
public bool Start()
348347
{
348+
if (_serverThread == null)
349+
{
350+
_serverThread = new Thread(StartListener);
351+
}
352+
349353
bool bStarted = true;
350354
// List Ethernet interfaces, so we can determine the server's address
351355
ListInterfaces();
@@ -381,6 +385,7 @@ public void Stop()
381385
_cancel = true;
382386
Thread.Sleep(100);
383387
_serverThread.Abort();
388+
_serverThread = null;
384389
Debug.WriteLine("Stoped server in thread ");
385390
}
386391

@@ -491,6 +496,10 @@ private void StartListener()
491496
while (!_cancel)
492497
{
493498
HttpListenerContext context = _listener.GetContext();
499+
if (context == null)
500+
{
501+
return;
502+
}
494503

495504
new Thread(() =>
496505
{
@@ -572,21 +581,20 @@ private void StartListener()
572581
if (mustAuthenticate && isAuthOk)
573582
{
574583
route.Callback.Invoke(null, new object[] { new WebServerEventArgs(context) });
575-
context.Response.Close();
576-
context.Close();
577584
}
578585
else
579586
{
580-
if (route.Authentication.AuthenticationType == AuthenticationType.Basic)
587+
if (route.Authentication != null && route.Authentication.AuthenticationType == AuthenticationType.Basic)
581588
{
582589
context.Response.Headers.Add("WWW-Authenticate", $"Basic realm=\"Access to {routeStr}\"");
583590
}
584591

585592
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
586593
context.Response.ContentLength64 = 0;
587-
context.Response.Close();
588-
context.Close();
589594
}
595+
596+
context.Response.Close();
597+
context.Close();
590598
}
591599

592600
if (!isRoute)
@@ -595,16 +603,15 @@ private void StartListener()
595603
{
596604
// Starting a new thread to be able to handle a new request in parallel
597605
CommandReceived.Invoke(this, new WebServerEventArgs(context));
598-
context.Response.Close();
599-
context.Close();
600606
}
601607
else
602608
{
603609
context.Response.StatusCode = 404;
604610
context.Response.ContentLength64 = 0;
605-
context.Response.Close();
606-
context.Close();
607611
}
612+
613+
context.Response.Close();
614+
context.Close();
608615
}
609616
}).Start();
610617

0 commit comments

Comments
 (0)