Exchanging Messages
Main article: Data Channels
Exchanging Messages and Data
Rainway provides Peers with the ability to create Data Channels, over which they can exchange arbitrary application-level binary data.
Sending messages over this channel is permitted any time two peers are connected end-to-end, whether they're streaming or not.
Initialization
The peer that requested the peer-to-peer connection is responsible for creating Data Channels. Here's how to create a Data Channel:
// given some peer object (see the previous tutorial page for an example)
// create a data channel
const channel = await peer.createDataChannel({
id: 'MyChannelLabel', // unique name for the channel
mode: DataChannelMode.Reliable, // see Data Channels main article
});
If you instead need to be notified when a remote peer creates a Data Channel, you can use the datachannel
event on a Peer
object. For example:
// given some peer object (see the previous tutorial page for an example)
// add a listener for when the remote peer creates a data channel
peer.addEventListener("datachannel", (channel) => {
// the channel may now be stored and used
});
Sending and receiving messages
To send a message to a peer, use the send
method on the DataChannel
:
// building on the above sample
// send a message over a data channel
channel.send("hello world");
The message will be received by the message
handler on the other Peer. For example, if that Peer is also using the Web SDK:
// given some data channel object
// add a listener for when new messages arrive
channel.addEventListener("message", (data) => console.log(data));
Updated over 2 years ago
Once you've made sure that you can send messages back and forth between peers, you're ready to start Streaming.