It is very simple, this code works, but only once, after the first time it is started, no other request is answered, as if after it runs once the StreamSocketListener has stopped.
public void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var detalhes = taskInstance.TriggerDetails as SocketActivityTriggerDetails;
if (detalhes.SocketInformation.SocketKind == SocketActivityKind.StreamSocketListener &&
detalhes.Reason == SocketActivityTriggerReason.ConnectionAccepted)
{
var list = detalhes.SocketInformation.StreamSocketListener;
list.ConnectionReceived += async (sender, args) =>
{
using (DataWriter escritor = new DataWriter(args.Socket.OutputStream))
{
escritor.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK");
await escritor.StoreAsync();
}
};
}
deferral.Complete();
}
The background task record is done with this code:
private void Registrar()
{
var tasks = BackgroundTaskRegistration.AllTasks;
int quant = tasks.Values.Count(x => x.Name == "SocketActivityBackgroundTask");
if (quant == 1)
{
task = tasks.Values.Single(x => x.Name == "SocketActivityBackgroundTask");
}
else
{
var socketTaskBuilder = new BackgroundTaskBuilder();
socketTaskBuilder.Name = "SocketActivityBackgroundTask";
socketTaskBuilder.TaskEntryPoint = "SocketActivityBackgroundTask.SocketActivityTask";
var trigger = new SocketActivityTrigger();
socketTaskBuilder.SetTrigger(trigger);
task = socketTaskBuilder.Register();
}
}
private async Task Iniciar()
{
var sockets = SocketActivityInformation.AllSockets;
if (!sockets.Keys.Contains(socketId))
{
StreamSocketListener socket = new StreamSocketListener();
socket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.DoNotWake);
await socket.BindServiceNameAsync(serverPort);
await Task.Delay(500);
await socket.CancelIOAsync();
socket.TransferOwnership(socketId);
}
}
The registry works and the task goes to the background, but it only works once, and this is the current problem, because the previous one was resolved but it was created.