docs.unity3d.com
    Show / Hide Table of Contents

    DataChannel

    The DataChannel feature passes text strings and binary between peers. It has the same features as WebSocket and uses UDP protocol, giving it several high performance characteristics.

    Note

    The package samples contains the DataChannel scene which demonstrates DataChannel features of the package.

    Creating DataChannel

    Multiple data channels can be created for a single peer. To create a data channel, first call the RTCPeerConnection's CreateDataChannel method.

    // Create the `RTCDataChannel` instance.
    var option = new RTCDataChannelInit();
    var channel = peerConnection.CreateDataChannel("test", option);
    

    If another peer creates a data channel, an OnDataChannel delegate will be executed as a call back.

    // Register the OnDataChannel delegate.
    peerConnnection.OnDataChannel = channel => 
    {
        // ...
    }
    

    Once the data channel is able to communicate between peers, the RTCDataChannel.OnOpen delegate will be executed. When the connection is closed, RTCDataChannel.OnClose will execute.

    Send messages

    Text strings or binary can be used for messages. Execute the RTCDataChannel.Send method to do so.

    // Send a text string
    string text = "hello";
    channel.Send(text);
    
    // Send byte array.
    byte[] data = System.Text.Encoding.ASCII.GetBytes(text);
    channel.Send(data);
    
    // Send a NativeArray.
    NativeArray<float> array = new NativeArray<float>(10, Allocator.Temp);
    channel.Send(array);
    

    Receive messages

    The RTCDataChannel.OnMessage delegate is used to receive messages.

    // Register OnMessage delegate.
    channel.OnMessage = bytes => 
    {
        // ...
    }
    
    Back to top
    Terms of use
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023