I have a program that controls a custom machine. I wanted to add some simple HTTP comms so I could control it from the network or other programs.
My server class is:
public class Server
{
private volatile bool stop = true;
private Action<string> methodOne;
public Server(Action<string> methodOne)
{
this.methodOne= methodOne;
}
public async Task StartAsync()
{
var prefix = "http://localhost:5005/";
HttpListener listener = new HttpListener();
listener.Prefixes.Add(prefix);
try
{
listener.Start();
stop = false;
}
catch (HttpListenerException hlex)
{
return;
}
while (listener.IsListening)
{
var context = await listener.GetContextAsync();
try
{
await ProcessRequestAsync(context);
}
catch (Exception ex)
{
Console.WriteLine("# EXCEPTION # " + ex.StackTrace);
}
if (stop == true) listener.Stop();
}
listener.Close();
}
public void Stop()
{
stop = true;
}
private async Task ProcessRequestAsync(HttpListenerContext context)
{
// Get the data from the HTTP stream
var body = await new StreamReader(context.Request.InputStream).ReadToEndAsync();
HttpListenerRequest request = context.Request;
if (request.RawUrl.StartsWith("/methodOne"))
{
//Get parameters
var options = context.Request.QueryString;
var keys = options.AllKeys;
//Run function
methodOne("some method parameter");
//Respond
byte[] b = Encoding.UTF8.GetBytes("ack");
context.Response.StatusCode = 200;
context.Response.KeepAlive = false;
context.Response.ContentLength64 = b.Length;
var output = context.Response.OutputStream;
await output.WriteAsync(b, 0, b.Length);
context.Response.Close();
}
}
}
I initialise the Server
by passing it the delegate for the function in the main view model that will be called, then start itwith server.StartAsync();
VS2017 gives me some advice that I didn't await server.StartAsync();
so thread will continue, but that is the functionality I want.
Any problems with making a server like this, using async and having it run on the main thread? All the server does is call methods in the view model, and there will usually be just one connection. The advantage for me is that being all on the same thread I don't have to worry about dispatching etc.
Task
for this. \$\endgroup\$