使用自訂資料通道透過已建立的遠端連線傳送自訂資料。
重要事項
自訂資料通道需要一個自訂的遠端應用程式和一個自訂播放器應用程式,因為這允許兩個自訂應用程式之間進行通訊。
提示
一個簡單的乒乓球範例可以在 Holographic Remoting 範例 GitHub 倉庫的遙控器和玩家範例中找到。 在 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() 建立資料通道的方法。 第一個參數是通道 ID,用於後續操作中識別資料通道。 第二個參數是優先權,用來指定該通道的優先權資料會被傳送到另一端。 遠端端的有效頻道 ID 範圍從 0 到 63 不等。 在玩家端,有效頻道 ID 從 64 到 127 不等。 有效的優先順序為 Low、 Medium、 或 High。
要開始在 遠端 建立資料通道:
// 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物件上的OnDataReceived事件IDataChannel。 註冊事件 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() 方法。 第一個參數是應該傳送的資料的 a winrt::array_view<const uint8_t> 。 第二個參數則指定資料應在接收位置,直到對方確認接收為止。
重要事項
在網路狀況不佳時,同一個資料封包可能會多次到達。 接收代碼必須能處理這種情況。
uint8_t data[] = {1};
m_customDataChannel.SendData(data, true);
關閉自訂資料通道
要關閉自訂資料通道,請使用以下 IDataChannel::Close() 方法。 當自訂資料通道關閉時,雙方都會收到事件通知 OnClosed 。
m_customDataChannel.Close();