问题
I am trying to develop a service to be deployed as an Azure Cloud Service. This service needs to listen for HttpRequests, and process them as they're received.
Thus far, I have created a simple Azure Cloud Service project in VS2017 with a single worker-role, which handles requests sent to /Localhost:8080/ like so:
public class WorkerRole : RoleEntryPoint
{
public override void Run()
{
this.runasync(this.cancellationTokenSource.Token).Wait();
}
finally
{
this.runCompleteEvent.Set();
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
bool result = base.OnStart();
Trace.TraceInformation("WorkerRole1 has been started");
return result;
}
private async Task RunAsync(CancellationToken cancellationToken)
{
await Listen("http://Localhost:8080/", 50, cancellationToken);
}
public async Task Listen(string prefix, int maxConcurrentRequests, CancellationToken token)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add(prefix);
listener.Start();
var requests = new HashSet<Task>();
for (int i = 0; i < maxConcurrentRequests; i++)
requests.Add(listener.GetContextAsync());
while (!token.IsCancellationRequested)
{
Task t = await Task.WhenAny(requests);
requests.Remove(t);
if (t is Task<HttpListenerContext>)
{
var context = (t as Task<HttpListenerContext>).Result;
requests.Add(ProcessRequestAsync(context));
requests.Add(listener.GetContextAsync());
}
}
}
public async Task ProcessRequestAsync(HttpListenerContext context)
{
//Specific handling logic here...
}
}
I will replace Localhost:8080 with the URL of the cloudservice once created.
I am using POSTMAN to send requests to the service for testing, but on the live environment, the requests will be sent from a server hosting a web-page; which will interact with users.
However, thus far, I have only been able to receive requests sent from/to the local machine I'm developing on.
How do I expose this HttpListener to remote requests, as a service running on Azure?
I am very new to working with Azure, and my search for helpful articles hasn't yielded a solid guide on how to set this up properly, so any help is appreciated.
来源:https://stackoverflow.com/questions/46933786/httplistener-in-azure-cloud-service