docs.unity3d.com
    Show / Hide Table of Contents

    Data Channel

    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.

    Creating Data Channel

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

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

    If another peer creates a data channel, an RTCPeerConnection.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 Message

    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 binary
    byte[] data = System.Text.Encoding.ASCII.GetBytes(text);
    channel.Send(data);
    

    Receive Message

    The RTCDataChannel.OnMessage delegate is used to receive messages.

    // Register OnMessage delegate
    channel.OnMessage = bytes => 
    {
        // ...
    }
    
    Back to top
    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