Uzak oturumlar aracılığıyla cihazları bağlama

Uzak Oturumlar özelliği, bir uygulamanın açık uygulama mesajlaşması veya Windows Holographic cihazları arasında holografik paylaşım için SpatialEntityStore gibi sistem tarafından yönetilen verilerin aracılı değişimi için bir oturum aracılığıyla diğer cihazlara bağlanmasına olanak tanır.

Uzak oturumlar herhangi bir Windows cihazı tarafından oluşturulabilir ve diğer kullanıcılar tarafından oturum açan cihazlar da dahil olmak üzere herhangi bir Windows cihazı katılma isteğinde bulunabilir (ancak oturumlar yalnızca davet edilebilir görünürlüğe sahip olabilir). Bu kılavuz, uzak oturumlardan yararlanan tüm önemli senaryolar için temel örnek kod sağlar. Bu kod mevcut bir uygulama projesine eklenebilir ve gerektiğinde değiştirilebilir. Uçtan uca uygulama için test oyunu örnek uygulamasına bakın).

Ön kurulum

remoteSystem özelliğini ekleme

Uygulamanızın uzak bir cihazda uygulama başlatması için, uygulama paketi bildiriminize bu özelliği eklemeniz remoteSystem gerekir. paket bildirimi tasarımcısını kullanarak Özellikler sekmesinde Uzaktan Sistem seçerek ekleyebilir veya projenizin Package.appxmanifest dosyasına aşağıdaki satırı el ile ekleyebilirsiniz.

<Capabilities>
   <uap3:Capability Name="remoteSystem"/>
</Capabilities>

Cihazda kullanıcılar arası bulmayı etkinleştirme

Uzak Oturumlar birden çok farklı kullanıcıyı bağlamaya yöneliktir, bu nedenle söz konusu cihazlarda Kullanıcılar Arası Paylaşımın etkinleştirilmesi gerekir. Bu, RemoteSystem sınıfında statik bir yöntemle sorgulanabilen bir sistem ayarıdır:

if (!RemoteSystem.IsAuthorizationKindEnabled(RemoteSystemAuthorizationKind.Anonymous)) {
	// The system is not authorized to connect to cross-user devices. 
	// Inform the user that they can discover more devices if they
	// update the setting to "Everyone nearby".
}

Bu ayarı değiştirmek için kullanıcının Ayarlar'ı açması gerekir. Sistem>Paylaşılan deneyimler>Cihazlar arası paylaşım menüsünde, kullanıcının sisteminin hangi cihazlarla paylaşabileceğini belirtebileceği bir açılan kutu vardır.

paylaşılan deneyimler ayarları sayfası

Gerekli ad alanlarını ekleyin

Bu kılavuzdaki tüm kod parçacıklarını kullanmak için sınıf dosyalarınızda aşağıdaki using deyimlere ihtiyacınız olacaktır.

using System.Runtime.Serialization.Json;
using Windows.Foundation.Collections;
using Windows.System.RemoteSystems;

Uzak oturum oluşturma

Uzak oturum örneği oluşturmak için RemoteSystemSessionController nesnesiyle başlamanız gerekir. Yeni bir oturum oluşturmak ve diğer cihazlardan gelen katılma isteklerini işlemek için aşağıdaki çerçeveyi kullanın.

public async void CreateSession() {
    
    // create a session controller
    RemoteSystemSessionController manager = new RemoteSystemSessionController("Bob’s Minecraft game");
    
    // register the following code to handle the JoinRequested event
    manager.JoinRequested += async (sender, args) => {
        // Get the deferral
        var deferral = args.GetDeferral();
        
        // display the participant (args.JoinRequest.Participant) on UI, giving the 
        // user an opportunity to respond
        // ...
        
        // If the user chooses "accept", accept this remote system as a participant
        args.JoinRequest.Accept();
    };
    
    // create and start the session
    RemoteSystemSessionCreationResult createResult = await manager.CreateSessionAsync();
    
    // handle the creation result
    if (createResult.Status == RemoteSystemSessionCreationStatus.Success) {
        // creation was successful, get a reference to the session
        RemoteSystemSession currentSession = createResult.Session;
        
        // optionally subscribe to the disconnection event
        currentSession.Disconnected += async (sender, args) => {
            // update the UI, using args.Reason
            //...
        };
    
        // Use session (see later section)
        //...
    
    } else if (createResult.Status == RemoteSystemSessionCreationStatus.SessionLimitsExceeded) {
        // creation failed. Optionally update UI to indicate that there are too many sessions in progress
    } else {
        // creation failed for an unknown reason. Optionally update UI
    }
}

Uzak oturumu yalnızca davetle erişilebilir yap

Uzak oturumunuzun genel olarak bulunabilir olmasını istemiyorsanız, bunu yalnızca davet edilebilir hale getirebilirsiniz. Yalnızca davet alan cihazlar katılma istekleri gönderebilir.

İşlem çoğunlukla yukarıdakiyle aynıdır, ancak RemoteSystemSessionController örneğini oluştururken, yapılandırılmış bir RemoteSystemSessionOptions nesnesi geçirmeniz gerekecek.

// define the session options with the invite-only designation
RemoteSystemSessionOptions sessionOptions = new RemoteSystemSessionOptions();
sessionOptions.IsInviteOnly = true;

// create the session controller
RemoteSystemSessionController manager = new RemoteSystemSessionController("Bob's Minecraft game", sessionOptions);

//...

Davet göndermek için, uzak sisteme bir referansa sahip olmalısınız (bu, normal uzak sistem keşfi yoluyla elde edilir). Bu başvuruyu oturum nesnesinin SendInvitationAsync yöntemine geçirmeniz yeterlidir. Bir oturumdaki tüm katılımcıların uzaktaki oturuma bir referansı vardır (sonraki bölüme bakın), böylece herhangi bir katılımcı davet gönderebilir.

// "currentSession" is a reference to a RemoteSystemSession.
// "guestSystem" is a previously discovered RemoteSystem instance
currentSession.SendInvitationAsync(guestSystem); 

Uzak oturumu keşfet ve katıl

Uzak oturumları bulma işlemi RemoteSystemSessionWatcher sınıfı tarafından işlenir ve tek tek uzak sistemleri bulmaya benzer.

public void DiscoverSessions() {
    
    // create a watcher for remote system sessions
    RemoteSystemSessionWatcher sessionWatcher = RemoteSystemSession.CreateWatcher();
    
    // register a handler for the "added" event
    sessionWatcher.Added += async (sender, args) => {
        
        // get a reference to the info about the discovered session
        RemoteSystemSessionInfo sessionInfo = args.SessionInfo;
        
        // Optionally update the UI with the sessionInfo.DisplayName and 
        // sessionInfo.ControllerDisplayName strings. 
        // Save a reference to this RemoteSystemSessionInfo to use when the
        // user selects this session from the UI
        //...
    };
    
    // Begin watching
    sessionWatcher.Start();
}

RemoteSystemSessionInfo örneği elde edildiğinde, ilgili oturumu denetleen cihaza bir birleştirme isteği göndermek için kullanılabilir. Kabul edilen bir katılma isteği, zaman uyumsuz bir şekilde katıldığı oturuma bir referans içeren bir RemoteSystemSessionJoinResult nesnesini geri dönecektir.

public async void JoinSession(RemoteSystemSessionInfo sessionInfo) {

    // issue a join request and wait for result.
    RemoteSystemSessionJoinResult joinResult = await sessionInfo.JoinAsync();
    if (joinResult.Status == RemoteSystemSessionJoinStatus.Success) {
        // Join request was approved

        // RemoteSystemSession instance "currentSession" was declared at class level.
        // Assign the value obtained from the join result.
        currentSession = joinResult.Session;
        
        // note connection and register to handle disconnection event
        bool isConnected = true;
        currentSession.Disconnected += async (sender, args) => {
            isConnected = false;

            // update the UI with args.Reason value
        };
        
        if (isConnected) {
            // optionally use the session here (see next section)
            //...
        }
    } else {
        // Join was unsuccessful.
        // Update the UI, using joinResult.Status value to show cause of failure.
    }
}

Bir cihaz aynı anda birden fazla oturuma katılabilir. Bu nedenle, birleştirme işlevinin her oturumla gerçek etkileşimden ayrılması istenebilir. RemoteSystemSession örneğine uygulamada referans sürdürüldüğü sürece, bu oturumda iletişim denenebilir.

Uzak oturum aracılığıyla iletileri ve verileri paylaşma

Mesajlar al

Oturum genelinde tek bir iletişim kanalını temsil eden RemoteSystemSessionMessageChannel örneğini kullanarak oturumdaki diğer katılımcı cihazlarla ileti ve veri alışverişi yapabilirsiniz. Başlatılır başlatılmaz, gelen iletileri dinlemeye başlar.

Uyarı

İletiler gönderilip alındıkten sonra bayt dizilerinden seri hale getirilmeli ve seri durumdan çıkarılmalıdır. Bu işlev aşağıdaki örneklerde yer alır, ancak daha iyi kod modülerliği için ayrı ayrı uygulanabilir. Bunun bir örneği için örnek uygulamaya bakın).

public async void StartReceivingMessages() {
    
    // Initialize. The channel name must be known by all participant devices 
    // that will communicate over it.
    RemoteSystemSessionMessageChannel messageChannel = new RemoteSystemSessionMessageChannel(currentSession, 
        "Everyone in Bob's Minecraft game", 
        RemoteSystemSessionMessageChannelReliability.Reliable);
    
    // write the handler for incoming messages on this channel
    messageChannel.ValueSetReceived += async (sender, args) => {
        
        // Update UI: a message was received from the participant args.Sender
        
        // Deserialize the message 
        // (this app must know what key to use and what object type the value is expected to be)
        ValueSet receivedMessage = args.Message;
        object rawData = receivedMessage["appKey"]);
        object value = new ExpectedType(); // this must be whatever type is expected

        using (var stream = new MemoryStream((byte[])rawData)) {
            value = new DataContractJsonSerializer(value.GetType()).ReadObject(stream);
        }
        
        // do something with the "value" object
        //...
    };
}

İleti gönderme

Kanal oluşturulduğunda, tüm oturum katılımcılarına ileti göndermek basittir.

public async void SendMessageToAllParticipantsAsync(RemoteSystemSessionMessageChannel messageChannel, object value){

    // define a ValueSet message to send
    ValueSet message = new ValueSet();
    
    // serialize the "value" object to send
    using (var stream = new MemoryStream()){
        new DataContractJsonSerializer(value.GetType()).WriteObject(stream, value);
        byte[] rawData = stream.ToArray();
            message["appKey"] = rawData;
    }
    
    // Send message to all participants. Ordering is not guaranteed.
    await messageChannel.BroadcastValueSetAsync(message);
}

Yalnızca belirli katılımcılara ileti göndermek için önce oturuma katılan uzak sistemlere başvuru almak için bir bulma işlemi başlatmanız gerekir. Bu, oturumun dışındaki uzak sistemleri bulma işlemine benzer. Oturumun katılımcı cihazlarını bulmak için RemoteSystemSessionParticipantWatcher örneği kullanın.

public void WatchForParticipants() {
    // "currentSession" is a reference to a RemoteSystemSession.
    RemoteSystemSessionParticipantWatcher watcher = currentSession.CreateParticipantWatcher();

    watcher.Added += (sender, participant) => {
        // save a reference to "participant"
        // optionally update UI
    };   

    watcher.Removed += (sender, participant) => {
        // remove reference to "participant"
        // optionally update UI
    };

    watcher.EnumerationCompleted += (sender, args) => {
        // Apps can delay data model render up until this point if they wish.
    };

    // Begin watching for session participants
    watcher.Start();
}

Oturum katılımcılarına yönelik referansların bir listesi alındığında, bunlardan herhangi bir grubuna ileti gönderebilirsiniz.

Tek bir katılımcıya mesaj göndermek için (ideal olarak kullanıcı tarafından ekranda seçilmiş olan), referansı aşağıdaki gibi bir yönteme geçirmeniz yeterlidir.

public async void SendMessageToParticipantAsync(RemoteSystemSessionMessageChannel messageChannel, RemoteSystemSessionParticipant participant, object value) {
    
    // define a ValueSet message to send
    ValueSet message = new ValueSet();
    
    // serialize the "value" object to send
    using (var stream = new MemoryStream()){
        new DataContractJsonSerializer(value.GetType()).WriteObject(stream, value);
        byte[] rawData = stream.ToArray();
            message["appKey"] = rawData;
    }

    // Send message to the participant
    await messageChannel.SendValueSetAsync(message,participant);
}

Birden çok katılımcıya ileti göndermek için (ideal olarak kullanıcı tarafından ekranda seçilidir), bunları bir liste nesnesine ekleyin ve listeyi aşağıdaki gibi bir yönteme geçirin.

public async void SendMessageToListAsync(RemoteSystemSessionMessageChannel messageChannel, IReadOnlyList<RemoteSystemSessionParticipant> myTeam, object value){

    // define a ValueSet message to send
    ValueSet message = new ValueSet();
    
    // serialize the "value" object to send
    using (var stream = new MemoryStream()){
        new DataContractJsonSerializer(value.GetType()).WriteObject(stream, value);
        byte[] rawData = stream.ToArray();
            message["appKey"] = rawData;
    }

    // Send message to specific participants. Ordering is not guaranteed.
    await messageChannel.SendValueSetToParticipantsAsync(message, myTeam);   
}