Create a background server

Asked

Viewed 134 times

2

It is quite 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 stops.


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();
}

Background job logging 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 record works and the task goes to the background, but it only works once, and this is the current problem, because the previous one was solved but this one was created.

  • 1

    Does it not mean "Create a SERVICE" ?

  • It’s just that I use Streamsocketlistener to host a web page, so that’s why I call it a server.

  • 1

    Now the question is clear enough?

  • Enter the code of how the server/service call/record is made

  • @rubStackOverflow Ready, need some more detail?

  • Now it’s easier to understand and try to identify the problem.

Show 1 more comment

1 answer

2

It’s not that simple, according to documentation in addition to the use of deferrals when an asynchronous function is performed, it is also recommended: (Re-register your background tasks during app launch.) Deregister` and re-register a task during application startup, among other recommendations.

foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
   if (cur.Value.Name != name) continue;
   cur.Value.Unregister(true);
}

As the process needs to run, apparently the use of the deferral.Complete(); , makes the task stop responding to requests SocketActivityTrigger.

I prepared a functional example with the implementations shown here, the source code is at the end of the answer.

Obviously the code needs to be improved but demonstrates the operation of a simple application UWP cliente/servidor based on communication via sockets


inserir a descrição da imagem aqui


Source Code:
https://github.com/rubgithub/ClientServerSocketUWP


References:

https://docs.microsoft.com/en-us/windows/uwp/launch-resume/guidelines-for-background-tasks https://social.technet.microsoft.com/wiki/contents/articles/36500.uwp-linux-socket-communication-handling-communciation-in-the-backgroundtask.aspx https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/WebSocket

  • Wow, what a complete answer, tomorrow I will analyze this solution you sent me, in case everything works out (I’m begging God to make it work), I will create a branch in my solution to improve your project.

  • Unfortunately your solution does not work as I expected, even I can connect to the server.

  • I believe that the problem proposed in the question works. Now if you are facing another kind of problem or have been trying something that is not within the scope of the question I suggest asking another question.

  • The problem is that I can’t make your project work, it just doesn’t work. I can’t get the server to receive a request through Edge at all :(

  • I believe the trigger SocketActivityTask is not fired in requests HTTP, at least in the tests performed here. I recommend doing further research and, if appropriate, supplementing the question or asking a new question.

  • He is, so much so that in the project of the question he is fired, but only once, because an error happens if I call the Transferownership.

  • What would be the call via browser? It would be http://localhost:123 for example?

  • I would use my cell phone, and it would be http://192.168. 0.102:1337

  • So... Any idea how to set up your project, I would even try to set up here, but I will now install VS 2017.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.