locked
[UWP] StreamSocket and backgroundtask - socket closed RRS feed

  • Question

  • Hello,

    could somebody explain to me, why when I start the app, the backgroundtask starts and the case SocketClosed is raised? It's always, when I start the app.

    Here is my code:

    Register bg task.

    var existingTask =
                    BackgroundTaskRegistration.AllTasks.FirstOrDefault(t => t.Value.Name == "SocketActivityTask").Value;
    
                if (existingTask == null)
                {
                    var taskbuilder = new BackgroundTaskBuilder();
                    taskbuilder.Name = "SocketActivityTask";
                    taskbuilder.TaskEntryPoint = "Tasks.SocketActivityTask";
                    //taskbuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
                    taskbuilder.IsNetworkRequested = true;
                    taskbuilder.SetTrigger(new SocketActivityTrigger());
                    existingTask = taskbuilder.Register();
                }
    
                taskid = existingTask.TaskId;
    

    Register socket:

    var socket = new StreamSocket();
                    socket.Control.KeepAlive = true;
                    socket.EnableTransferOwnership(taskid);
                    await socket.ConnectAsync(new HostName("127.0.0.1"), "99");
                    var reader = new DataReader(socket.InputStream);
                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    await reader.LoadAsync(128);
                    await socket.CancelIOAsync();
                    socket.TransferOwnership("SOCKET");

    and Bgtask:

    private BackgroundTaskDeferral _deferral;
            public async void Run(IBackgroundTaskInstance taskInstance)
            {
                _deferral = taskInstance.GetDeferral();
                var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails;
                var socketInformation = details.SocketInformation;
                switch (details.Reason)
                {
                    case SocketActivityTriggerReason.SocketActivity:
                        var socket = socketInformation.StreamSocket;
                        DataReader reader = new DataReader(socket.InputStream);
                        reader.InputStreamOptions = InputStreamOptions.Partial;
                        await reader.LoadAsync(250);
                        var dataString = reader.ReadString(reader.UnconsumedBufferLength);
                        ShowToast(dataString);
                        Current.Text = dataString;
    
                        socket.TransferOwnership(socketInformation.Id);
                        break;
                    case SocketActivityTriggerReason.KeepAliveTimerExpired:
                        socket = socketInformation.StreamSocket;
                        DataWriter writer = new DataWriter(socket.OutputStream);
                        writer.WriteBytes(Encoding.UTF8.GetBytes("Keep alive"));
                        await writer.StoreAsync();
                        writer.DetachStream();
                        writer.Dispose();
                        socket.TransferOwnership(socketInformation.Id);
                        break;
                    case SocketActivityTriggerReason.SocketClosed:
                        socket = new StreamSocket();
                        socket.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.Wake);
                        var hostname = "127.0.0.1";
                        var port = "99";
                        await socket.ConnectAsync(new HostName(hostname), port);
                        socket.TransferOwnership("SOCKET");
                        break;
                    default:
                        break;
                }
                _deferral.Complete();
            }


    Thursday, July 28, 2016 7:16 AM

Answers

  • Hi Pupino,

    >>” But why, when I close the app and run it again, the backgroundtask is fired with case SocketClosed?”

    It’s because it would call the “socket.TransferOwnership” method when you restart your app.

    Transfers ownership of the StreamSocket to the socket brokering service, which monitors socket activity and notifies the app through a background task if there is any activity. Specifies a new SocketActivityContext and a keep alive time for the socket.”

    Best Regards,

    Xavier Eoro


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Monday, August 1, 2016 6:51 AM

All replies

  • Hi Pupino,

    I have checked your code snippet. I cannot find any issues. I suggest you could check MS official code sample, I have run it in my side, it worked well. You could refer to that sample to check your code whether there’re some issues.

    Here’s code sample: Socket activity trigger stream socket sample 

    Best Regards,

    Xavier Eoro


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, July 29, 2016 6:22 AM
  • Hello,

    I'm using StreamSocket and SocketActivityTrigger. When I shutdown the server, background task is fired with case SocketClosed, where I try to re-connect and when the server is off, connection fails. After some time I turn on the server but the app won't to connect. There's no activity on socket. Is socket broker service trying to connect to server in some intervals or I need to run the app and connect again to server? It should be automatically, my god. What if I turn off the server for one week and then turn on, my app will not receive any data. Could somebody explain to me, how it works? because documentation is very very poor.

    • Merged by Xavier Xie-MSFT Monday, August 1, 2016 5:49 AM the same question
    Friday, July 29, 2016 7:31 AM
  • But why, when I close the app and run it again, the backgroundtask is fired with case SocketClosed?
    Friday, July 29, 2016 9:20 AM
  • Hi Pupino,

    >>” But why, when I close the app and run it again, the backgroundtask is fired with case SocketClosed?”

    It’s because it would call the “socket.TransferOwnership” method when you restart your app.

    Transfers ownership of the StreamSocket to the socket brokering service, which monitors socket activity and notifies the app through a background task if there is any activity. Specifies a new SocketActivityContext and a keep alive time for the socket.”

    Best Regards,

    Xavier Eoro


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Monday, August 1, 2016 6:51 AM