使用全像攝影遠端和Windows Mixed Reality API 的自訂資料通道

使用自訂資料通道,透過已建立的遠端連線傳送自訂資料。

重要

自訂資料通道需要自訂遠端應用程式和自訂播放機應用程式,因為它允許兩個自訂應用程式之間的通訊。

提示

您可以在 Holographic Remoting 範例 github 存放庫內的遠端和播放機範例中找到簡單的 ping-pong 範例。 將 SampleRemoteApp.h / SamplePlayerMain.h 檔案內的批註取消批 #define ENABLE_CUSTOM_DATA_CHANNEL_SAMPLE 注,以啟用範例程式碼。

建立自訂資料通道

若要建立自訂資料通道,需要下欄欄位:

std::recursive_mutex m_customDataChannelLock;
winrt::Microsoft::Holographic::AppRemoting::IDataChannel m_customDataChannel = nullptr;
winrt::Microsoft::Holographic::AppRemoting::IDataChannel::OnDataReceived_revoker m_customChannelDataReceivedEventRevoker;
winrt::Microsoft::Holographic::AppRemoting::IDataChannel::OnClosed_revoker m_customChannelClosedEventRevoker;

成功建立連線之後,您可以從遠端、玩家端或兩者建立新的資料通道。 RemoteCoNtext 和 PlayerCoNtext 都提供建立 CreateDataChannel() 資料通道的方法。 第一個參數是通道識別碼,用來識別後續作業中的資料通道。 第二個參數是指定此通道的優先順序資料傳送至另一端的優先順序。 在遠端,有效的通道識別碼範圍從 0 到 63。 在玩家端,有效的通道識別碼介於 64 到 127 之間。 有效的優先順序為 LowMediumHigh

若要開始在 遠端 建立資料通道:

// Valid channel ids for channels created on the remote side are 0 up to and including 63
m_remoteContext.CreateDataChannel(0, DataChannelPriority::Low);

若要開始在 玩家 端建立資料通道:

// Valid channel ids for channels created on the player side are 64 up to and including 127
m_playerContext.CreateDataChannel(64, DataChannelPriority::Low);

注意

若要建立新的自訂資料通道,遠端或播放機) 只需要呼叫 CreateDataChannel 方法 (一端。

處理自訂資料通道事件

若要建立自訂資料通道, OnDataChannelCreated 必須在玩家和遠端端) 上 (處理事件。 它會在任一端 IDataChannel 建立使用者資料通道並提供 物件時觸發,該物件可用來透過此通道傳送和接收資料。

若要在事件上 OnDataChannelCreated 註冊接聽程式:

m_onDataChannelCreatedEventRevoker = m_remoteContext.OnDataChannelCreated(winrt::auto_revoke,
    [this](const IDataChannel& dataChannel, uint8_t channelId)
    {
        std::lock_guard lock(m_customDataChannelLock);
        m_customDataChannel = dataChannel;

        // Register to OnDataReceived and OnClosed event of the data channel here, see below...
    });

若要在收到資料時收到通知,請在處理常式提供 OnDataChannelCreated 的物件上 IDataChannel 註冊 OnDataReceived 事件。 註冊事件 OnClosed ,以在資料通道關閉時收到通知。

m_customChannelDataReceivedEventRevoker = m_customDataChannel.OnDataReceived(winrt::auto_revoke, 
    [this]()
    {
        // React on data received via the custom data channel here.
    });

m_customChannelClosedEventRevoker = m_customDataChannel.OnClosed(winrt::auto_revoke,
    [this]()
    {
        // React on data channel closed here.

        std::lock_guard lock(m_customDataChannelLock);
        if (m_customDataChannel)
        {
            m_customDataChannel = nullptr;
        }
    });

傳送資料

若要透過自訂資料通道傳送資料,請使用 IDataChannel::SendData() 方法。 第一個 winrt::array_view<const uint8_t> 參數是應傳送之資料的 。 第二個參數會指定資料應該重新傳送的位置,直到另一端認可接收為止。

重要

如果網路狀況不良,相同的資料封包可能會多次送達。 接收程式碼必須能夠處理這種情況。

uint8_t data[] = {1};
m_customDataChannel.SendData(data, true);

關閉自訂資料通道

若要關閉自訂資料通道,請使用 IDataChannel::Close() 方法。 一旦自訂資料通道關閉,這兩端就會收到 OnClosed 事件通知。

m_customDataChannel.Close();

另請參閱