docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Class RTCDataChannel

    Creates a new RTCDataChannel for peer-to-peer data exchange, using the specified label and options.

    Inheritance
    object
    RefCountedObject
    RTCDataChannel
    Implements
    IDisposable
    Inherited Members
    RefCountedObject.disposed
    Namespace: Unity.WebRTC
    Assembly: Unity.WebRTC.dll
    Syntax
    public class RTCDataChannel : RefCountedObject, IDisposable
    Remarks

    The CreateDataChannel method establishes a bidirectional communication channel between peers, identified by a unique label. This channel allows for the transmission of arbitrary data, such as text or binary, directly between connected peers without the need for a traditional server. The optional parameters provide flexibility in controlling the behavior of the data channel, including options for reliability and ordering of messages. It's essential for applications to configure these channels according to their specific communication needs.

    Examples
    var initOption = new RTCDataChannelInit();
    var peerConnection = new RTCPeerConnection();
    var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
    dataChannel.OnMessage = (event) => {
        Debug.LogFormat("Received: {0}.",${event.data});
    };
    
    dataChannel.OnOpen = () => {
        Debug.Log("DataChannel opened.");
    };
    
    dataChannel.OnClose = () => {
        Debug.Log("DataChannel closed.");
    };

    Properties

    BufferedAmount

    Returns the number of bytes of data currently queued to be sent over the data channel.

    Declaration
    public ulong BufferedAmount { get; }
    Property Value
    Type Description
    ulong
    Remarks

    The BufferedAmount property indicates the number of bytes of data currently queued to be sent over the data channel. This value represents the amount of data buffered on the sender side that has not yet been transmitted to the network. Monitoring this property helps developers understand and manage flow control, allowing for adjustments to data transmission rates to avoid congestion. In scenarios where this value grows unexpectedly, it could indicate network congestion or slow peer processing, prompting the need to throttle data sending. Proper use of this property ensures that applications can maintain efficient data flow while mitigating potential bottlenecks.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelBufferedAmountExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            // Periodically check the BufferedAmount
            InvokeRepeating("CheckBufferedAmount", 1.0f, 1.0f);
        }
    
        private void CheckBufferedAmount()
        {
            // Log the BufferedAmount of the data channel
            Debug.Log("DataChannel BufferedAmount: " + dataChannel.BufferedAmount);
        }
    
        private void OnDestroy()
        {
            // Ensure to clean up the data channel
            if (dataChannel != null)
            {
                dataChannel.Close();
            }
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Id

    Returns an ID number (between 0 and 65,534) which uniquely identifies the RTCDataChannel.

    Declaration
    public int Id { get; }
    Property Value
    Type Description
    int
    Remarks

    The Id property provides a unique identifier for the data channel, typically assigned during the channel's creation. This identifier is used internally to differentiate between multiple data channels associated with a single RTCPeerConnection. Understanding and referencing these IDs can be crucial when managing complex peer-to-peer communication setups where multiple channels are active. The ID is automatically generated unless explicitly set during manual channel negotiation.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelIdExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            Debug.Log("DataChannel ID: " + dataChannel.Id);
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Label

    Returns a string description of the data channel, which is not required to be unique.

    Declaration
    public string Label { get; }
    Property Value
    Type Description
    string
    Remarks

    The Label property specifies a name for the data channel, which is set when the channel is created. This label is useful for identifying the purpose of the data channel, such as distinguishing between channels dedicated to different types of data or tasks. While labels are not required to be unique, they provide meaningful context within an application, aiding in organization and management of multiple channels. Developers can utilize labels to group channels by function or to describe their role in the communication process.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelLabelExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            Debug.Log("DataChannel Label: " + dataChannel.Label);
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    MaxRetransmitTime

    Returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or null.

    Declaration
    public ushort MaxRetransmitTime { get; }
    Property Value
    Type Description
    ushort
    Remarks

    The MaxRetransmitTime property sets the maximum duration, in milliseconds, that the data channel will attempt to retransmit a message in unreliable mode. This constraint ensures that if a message cannot be delivered within the specified time frame, the channel will cease retransmission attempts. It is particularly useful for applications where timing is critical, allowing developers to limit delays potentially caused by prolonged retransmission efforts. By defining this timeout, applications can maintain performance efficiency while handling network fluctuations. If not set, the retransmission will continue based on other reliability settings, possibly yielding variable delays. ///

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelMaxRetransmitTimeExample : MonoBehaviour
    {
        private void Start()
        {
            // Create an instance of RTCDataChannelInit with a specific MaxRetransmitTime
            var initOption = new RTCDataChannelInit
            {
                MaxRetransmitTime = 5000 // Set the maximum retransmit time in milliseconds
            };
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            // Log the MaxRetransmitTime of the data channel
            Debug.Log("DataChannel MaxRetransmitTime: " + dataChannel.MaxRetransmitTime);
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    MaxRetransmits

    Returns the maximum number of times the browser should try to retransmit a message before giving up.

    Declaration
    public ushort MaxRetransmits { get; }
    Property Value
    Type Description
    ushort
    Remarks

    The MaxRetransmits property defines the upper limit on the number of times a message will be retransmitted if initial delivery fails. This setting is particularly valuable in conditions where reliable delivery is necessary, but the application is sensitive to potential delays caused by continuous retransmission attempts. By specifying a limit, developers can balance the need for message reliability with the potential impact on performance and latency. If no retransmit limit is set, the data channel may continue to attempt message delivery until it succeeds, which might not be suitable for all applications. ///

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelMaxRetransmitsExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit
            {
                MaxRetransmits = 10
            };
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            Debug.Log("DataChannel MaxRetransmits: " + dataChannel.MaxRetransmits);
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Negotiated

    Indicates whether the RTCDataChannel's connection is negotiated by the Web app or by the WebRTC layer.

    Declaration
    public bool Negotiated { get; }
    Property Value
    Type Description
    bool
    Remarks

    The Negotiated property indicates whether the data channel's connection parameters were explicitly negotiated by the application or automatically handled by the WebRTC implementation. When set to true, it allows developers to manually manage the channel setup including selecting the channel ID, offering greater control over communication specifics. This is especially useful in advanced scenarios where integration with complex signaling servers or custom negotiation processes are needed. If false, the WebRTC stack automatically negotiates the channel's configuration, simplifying the setup but providing less granular control. Proper switching between these modes ensures the application meets its communication requirements effectively.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelNegotiatedExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit
            {
                Negotiated = true // Set this to true if manually negotiating the channel
            };
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            // Log the Negotiated property of the data channel
            Debug.Log("DataChannel Negotiated: " + dataChannel.Negotiated);
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    OnClose

    Delegate to be called when the data channel's message transport mechanism is closed.

    Declaration
    public DelegateOnClose OnClose { get; set; }
    Property Value
    Type Description
    DelegateOnClose
    Remarks

    The close event is sent to the onclose event handler on an RTCDataChannel instance when the data transport for the data channel has closed. Before any further data can be transferred using RTCDataChannel, a new 'RTCDataChannel' instance must be created. This event is not cancelable and does not bubble.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelCloseExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnClose = () => {
                Debug.Log("DataChannel closed.");
            };
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    OnError

    Delegate to be called when errors occur.

    Declaration
    public DelegateOnError OnError { get; set; }
    Property Value
    Type Description
    DelegateOnError
    Remarks

    The OnClose delegate is triggered when the data channel's transport layer is terminated, signifying the channel's transition to a closed state. This event serves as a cue for the application to release resources, update the user interface, or handle any clean-up operations necessary to gracefully end the communication session. Understanding this transition is vital for managing the lifecycle of data exchanges between peers.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelErrorExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnError = (e) => {
                Debug.LogError("DataChannel error: " + e.message);
            };
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    OnMessage

    Delegate to be called when a message has been received from the remote peer.

    Declaration
    public DelegateOnMessage OnMessage { get; set; }
    Property Value
    Type Description
    DelegateOnMessage
    Remarks

    The OnMessage delegate is invoked whenever a message is received over the data channel from the remote peer. This provides the application an opportunity to process the received data, which could include tasks such as updating the user interface, storing information, or triggering specific logic. The message is delivered as a byte array, offering flexibility to handle both text and binary data formats.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelMessageExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnMessage = (e) => {
                Debug.LogFormat("Received: {0}.", e.data);
            };
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    OnOpen

    Delegate to be called when the data channel's message transport mechanism is opened or reopened.

    Declaration
    public DelegateOnOpen OnOpen { get; set; }
    Property Value
    Type Description
    DelegateOnOpen
    Remarks

    The OnOpen delegate is triggered when the data channel successfully establishes its underlying transport mechanism. This state transition indicates that the channel is ready for data transmission, providing an opportunity for the application to initialize any required states or notify the user that the channel is ready to use. It is a critical event for setting up initial data exchanges between peers.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelOpenExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () => {
                Debug.Log("DataChannel opened.");
            };
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Ordered

    Determines whether the data channel ensures the delivery of messages in the order they were sent.

    Declaration
    public bool Ordered { get; }
    Property Value
    Type Description
    bool
    Remarks

    The Ordered property controls whether the data channel delivers messages in the sequence they were dispatched. If set to true, messages will arrive in the exact order sent, ensuring consistent data flow, which can be critical for applications where order is important. If false, the data channel allows out-of-order delivery to potentially enhance transmission speed but is best suited for applications where strict order isn't a concern. ///

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelOrderedExample : MonoBehaviour
    {
        private void Start()
        {
            // Create an instance of RTCDataChannelInit with the Ordered property set
            var initOption = new RTCDataChannelInit
            {
                Ordered = false // Set to false if you don't require reliable and ordered delivery
            };
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            // Log the Ordered property of the data channel
            Debug.Log("DataChannel Ordered: " + dataChannel.Ordered);
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Protocol

    Returns the subprotocol being used by the data channel to transmit and process messages.

    Declaration
    public string Protocol { get; }
    Property Value
    Type Description
    string
    Remarks

    The Protocol property retrieves the subprotocol negotiated for this data channel, which governs the rules for message format and communication behavior between peers. This property is critical for ensuring compatibility and understanding between different systems or applications using the channel, especially when custom protocols are used. If no protocol was specified during the data channel's creation, this property returns an empty string, indicating that no particular subprotocol is in effect.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelProtocolExample : MonoBehaviour
    {
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            var dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            Debug.Log("DataChannel Protocol: " + dataChannel.Protocol);
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    ReadyState

    Returns an enum of the RTCDataChannelState which shows the state of the channel.

    Declaration
    public RTCDataChannelState ReadyState { get; }
    Property Value
    Type Description
    RTCDataChannelState
    Remarks

    Send(string) method must be called when the state is Open.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelReadyStateExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            // Log the initial ReadyState of the data channel
            Debug.Log("DataChannel ReadyState: " + dataChannel.ReadyState);
    
            // Optionally, you can periodically check the ReadyState
            InvokeRepeating("CheckReadyState", 1.0f, 1.0f);
        }
    
        private void CheckReadyState()
        {
            // Log the current ReadyState of the data channel
            Debug.Log("DataChannel ReadyState: " + dataChannel.ReadyState);
        }
    
        private void OnDestroy()
        {
            // Ensure to clean up the data channel
            if (dataChannel != null)
            {
                dataChannel.Close();
            }
        }
    }
    See Also
    RTCDataChannelState

    Methods

    Close()

    Closes the RTCDataChannel. Either peer is permitted to call this method to initiate closure of the channel.

    Declaration
    public void Close()
    Remarks

    Closure of the data channel is not instantaneous. Most of the process of closing the connection is handled asynchronously; you can detect when the channel has finished closing by watching for a close event on the data channel.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelCloseExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () =>
            {
                Debug.Log("DataChannel opened.");
            };
    
            dataChannel.OnClose = () =>
            {
                Debug.Log("DataChannel closed.");
            };
    
            // Assume some operation has been completed and we need to close the data channel
            Invoke("CloseDataChannel", 5.0f); // Close the channel after 5 seconds
        }
    
        private void CloseDataChannel()
        {
            if (dataChannel != null)
            {
                dataChannel.Close();
                Debug.Log("DataChannel has been closed manually.");
            }
        }
    
        private void OnDestroy()
        {
            // Clean up the data channel when the GameObject is destroyed
            if (dataChannel != null)
            {
                dataChannel.Close();
            }
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Dispose()

    Release all the resources RTCDataChannel instance has allocated.

    Declaration
    public override void Dispose()
    Overrides
    RefCountedObject.Dispose()
    Remarks

    The Dispose method leaves the RTCDataChannel in an unusable state. After calling Dispose, you must release all references to the RTCDataChannel so the garbage collector can reclaim the memory that the RTCDataChannel was occupying.

    Note: Always call Dispose before you release your last reference to the RTCDataChannel. Otherwise, the resources it is using will not be freed until the garbage collector calls the Finalize method of the object.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelDisposeExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            // Log creation of the data channel
            Debug.Log("DataChannel created.");
    
            // Simulate some operations
            Invoke("CleanUp", 5.0f); // Automatically clean up after 5 seconds
        }
    
        private void CleanUp()
        {
            // Clean up resources
            if (dataChannel != null)
            {
                dataChannel.Close(); // Close the channel
                dataChannel.Dispose(); // Explicitly dispose the channel
                Debug.Log("DataChannel disposed.");
            }
        }
    
        private void OnDestroy()
        {
            // Ensure cleanup on destruction
            CleanUp();
        }
    }
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    ~RTCDataChannel()

    Declaration
    protected ~RTCDataChannel()
    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Send(byte[])

    Sends data across the data channel to the remote peer.

    Declaration
    public void Send(byte[] msg)
    Parameters
    Type Name Description
    byte[] msg

    The byte array to be sent to the remote peer.

    Remarks

    This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelSendByteArrayExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () =>
            {
                Debug.Log("DataChannel opened.");
                SendMessage(new byte[] { 0x01, 0x02, 0x03 });
            };
    
            dataChannel.OnMessage = (e) =>
            {
                if (e.binary)
                {
                    Debug.Log("Received binary message of length: " + e.data.Length);
                }
                else
                {
                    Debug.Log("Received message: " + e.data);
                }
            };
        }
    
        public void SendMessage(byte[] message)
        {
            if (dataChannel.ReadyState == RTCDataChannelState.Open)
            {
                dataChannel.Send(message);
                Debug.Log("Sent binary message of length: " + message.Length);
            }
            else
            {
                Debug.LogWarning("DataChannel is not open. Cannot send message.");
            }
        }
    
        private void OnDestroy()
        {
            if (dataChannel != null)
            {
                dataChannel.Close();
                dataChannel.Dispose();
            }
        }
    }
    Exceptions
    Type Condition
    InvalidOperationException

    The method throws InvalidOperationException when ReadyState is not Open.

    See Also
    ReadyState

    Send(IntPtr, int)

    Sends data across the data channel to the remote peer.

    Declaration
    public void Send(IntPtr msgPtr, int length)
    Parameters
    Type Name Description
    IntPtr msgPtr

    A pointer to the memory location containing the data to be sent.

    int length

    The length of the data, in bytes, to be sent from the specified memory location.

    Remarks

    This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.

    Examples
    using System;
    using Unity.Collections;
    using Unity.Collections.LowLevel.Unsafe;
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelSendVoidPointerExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () =>
            {
                Debug.Log("DataChannel opened.");
    
                byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };
                unsafe
                {
                    fixed (byte* dataPtr = data)
                    {
                        Send(dataPtr, data.Length);
                    }
                }
            };
    
            dataChannel.OnMessage = (e) =>
            {
                if (e.binary)
                {
                    Debug.Log("Received binary message of length: " + e.data.Length);
                }
            };
        }
    
    
        private void OnDestroy()
        {
            if (dataChannel != null)
            {
                dataChannel.Close();
                dataChannel.Dispose();
            }
        }
    }
    Exceptions
    Type Condition
    InvalidOperationException

    Thrown when the ReadyState is not Open.

    See Also
    ReadyState

    Send(string)

    Sends data across the data channel to the remote peer.

    Declaration
    public void Send(string msg)
    Parameters
    Type Name Description
    string msg

    The string message to be sent to the remote peer.

    Remarks

    This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.

    Examples
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelSendExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () =>
            {
                Debug.Log("DataChannel opened.");
                SendMessage("Hello, WebRTC!");
            };
    
            dataChannel.OnMessage = (e) =>
            {
                Debug.Log("Received message: " + e.data);
            };
        }
    
        private void SendMessage(string message)
        {
            if (dataChannel.ReadyState == RTCDataChannelState.Open)
            {
                dataChannel.Send(message);
                Debug.Log("Sent message: " + message);
            }
            else
            {
                Debug.LogWarning("DataChannel is not open. Cannot send message.");
            }
        }
    
        private void OnDestroy()
        {
            if (dataChannel != null)
            {
                dataChannel.Close();
                dataChannel.Dispose();
            }
        }
    }
    Exceptions
    Type Condition
    InvalidOperationException

    The method throws InvalidOperationException when ReadyState is not Open.

    See Also
    ReadyState

    Send(void*, int)

    Sends data across the data channel to the remote peer.

    Declaration
    public void Send(void* msgPtr, int length)
    Parameters
    Type Name Description
    void* msgPtr

    A pointer to the memory location containing the data to be sent.

    int length

    The length of the data, in bytes, to be sent from the specified memory location.

    Remarks

    This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.

    Exceptions
    Type Condition
    InvalidOperationException

    Thrown when the ReadyState is not Open.

    See Also
    ReadyState

    Send<T>(NativeArray<T>)

    Sends data across the data channel to the remote peer.

    Declaration
    public void Send<T>(NativeArray<T> msg) where T : struct
    Parameters
    Type Name Description
    NativeArray<T> msg

    The NativeArray containing the data to be sent to the remote peer.

    Type Parameters
    Name Description
    T

    The type of elements stored in the NativeArray, which must be a value type.

    Remarks

    This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.

    Examples
    using System;
    using Unity.Collections;
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelSendNativeArrayExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () =>
            {
                Debug.Log("DataChannel opened.");
                var nativeArray = new NativeArray<byte>(new byte[] { 0x01, 0x02, 0x03 }, Allocator.Temp);
                Send(nativeArray);
                nativeArray.Dispose();
            };
    
            dataChannel.OnMessage = (e) =>
            {
                if (e.binary)
                {
                    Debug.Log("Received binary message of length: " + e.data.Length);
                }
            };
        }
    
        public unsafe void Send<T>(NativeArray<T> msg) where T : struct
        {
            if (dataChannel.ReadyState == RTCDataChannelState.Open)
            {
                void* ptr = msg.GetUnsafePtr();
                byte[] bytes = new byte[msg.Length * UnsafeUtility.SizeOf<T>()];
                System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), bytes, 0, bytes.Length);
                dataChannel.Send(bytes);
                Debug.Log("Sent binary message of length: " + bytes.Length);
            }
            else
            {
                Debug.LogWarning("DataChannel is not open. Cannot send message.");
            }
        }
    
        private void OnDestroy()
        {
            if (dataChannel != null)
            {
                dataChannel.Close();
                dataChannel.Dispose();
            }
        }
    }
    Exceptions
    Type Condition
    InvalidOperationException

    The method throws InvalidOperationException when ReadyState is not Open.

    See Also
    CreateDataChannel(string, RTCDataChannelInit)

    Send<T>(ReadOnly)

    Sends data across the data channel to the remote peer.

    Declaration
    public void Send<T>(NativeArray<T>.ReadOnly msg) where T : struct
    Parameters
    Type Name Description
    NativeArray<T>.ReadOnly msg

    The read-only NativeArray containing the data to be sent to the remote peer.

    Type Parameters
    Name Description
    T

    The type of elements stored in the read-only NativeArray, which must be a value type.

    Remarks

    This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.

    Examples
    using System;
    using Unity.Collections;
    using Unity.Collections.LowLevel.Unsafe;
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelSendNativeArrayReadOnlyExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () =>
            {
                Debug.Log("DataChannel opened.");
                var nativeArray = new NativeArray<byte>(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 }, Allocator.Temp);
                var readOnlyArray = nativeArray.AsReadOnly();
                Send(readOnlyArray);
                nativeArray.Dispose();
            };
    
            dataChannel.OnMessage = (e) =>
            {
                if (e.binary)
                {
                    Debug.Log("Received binary message of length: " + e.data.Length);
                }
            };
        }
    
        public unsafe void Send<T>(NativeArray<T>.ReadOnly msg) where T : struct
        {
            if (dataChannel.ReadyState == RTCDataChannelState.Open)
            {
                void* ptr = msg.GetUnsafeReadOnlyPtr();
                byte[] bytes = new byte[msg.Length * UnsafeUtility.SizeOf<T>()];
                System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), bytes, 0, bytes.Length);
                dataChannel.Send(bytes);
                Debug.Log("Sent binary message of length: " + bytes.Length);
            }
            else
            {
                Debug.LogWarning("DataChannel is not open. Cannot send message.");
            }
        }
    
        private void OnDestroy()
        {
            if (dataChannel != null)
            {
                dataChannel.Close();
                dataChannel.Dispose();
            }
        }
    }
    Exceptions
    Type Condition
    InvalidOperationException

    Thrown when the ReadyState is not Open.

    See Also
    ReadyState

    Send<T>(NativeSlice<T>)

    Sends data across the data channel to the remote peer.

    Declaration
    public void Send<T>(NativeSlice<T> msg) where T : struct
    Parameters
    Type Name Description
    NativeSlice<T> msg

    The NativeSlice containing the data to be sent to the remote peer.

    Type Parameters
    Name Description
    T

    The type of elements stored in the NativeSlice, which must be a value type.

    Remarks

    This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.

    Examples
    using System;
    using Unity.Collections;
    using Unity.Collections.LowLevel.Unsafe;
    using UnityEngine;
    using Unity.WebRTC;
    
    public class DataChannelSendNativeSliceExample : MonoBehaviour
    {
        private RTCDataChannel dataChannel;
    
        private void Start()
        {
            var initOption = new RTCDataChannelInit();
            var peerConnection = new RTCPeerConnection();
            dataChannel = peerConnection.CreateDataChannel("test channel", initOption);
    
            dataChannel.OnOpen = () =>
            {
                Debug.Log("DataChannel opened.");
                var nativeArray = new NativeArray<byte>(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 }, Allocator.Temp);
                var nativeSlice = new NativeSlice<byte>(nativeArray, 1, 3); // Slice from index 1 to 3
                Send(nativeSlice);
                nativeArray.Dispose();
            };
    
            dataChannel.OnMessage = (e) =>
            {
                if (e.binary)
                {
                    Debug.Log("Received binary message of length: " + e.data.Length);
                }
            };
        }
    
        public unsafe void Send<T>(NativeSlice<T> msg) where T : struct
        {
            if (dataChannel.ReadyState == RTCDataChannelState.Open)
            {
                void* ptr = msg.GetUnsafeReadOnlyPtr();
                byte[] bytes = new byte[msg.Length * UnsafeUtility.SizeOf<T>()];
                System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), bytes, 0, bytes.Length);
                dataChannel.Send(bytes);
                Debug.Log("Sent binary message of length: " + bytes.Length);
            }
            else
            {
                Debug.LogWarning("DataChannel is not open. Cannot send message.");
            }
        }
    
        private void OnDestroy()
        {
            if (dataChannel != null)
            {
                dataChannel.Close();
                dataChannel.Dispose();
            }
        }
    }
    Exceptions
    Type Condition
    InvalidOperationException

    Thrown when the ReadyState is not Open.

    See Also
    ReadyState

    Implements

    IDisposable

    See Also

    CreateDataChannel(string, RTCDataChannelInit)
    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)