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.
peer.createDataChannel({ id: "Messages", mode: RainwayChannelMode.Reliable });
The peer that accepted the connection request then gets a DataChannel
event for each created channel.
peer.addEventListener("datachannel", (ev) => {
const dc = ev.data; // I am the created data channel
});
Sending and receiving messages
To send a message, use send
on the DataChannel.
dc.send("hello world");
Messages from the remote Peer are received by the OnPeerMessage
handler:
dc.addEventListener("message", (ev) => {
// Uint8Array data, composing the message
const data = ev.data;
// same data, interpreted as a utf-8 string
const str = ev.asString;
});
Updated over 2 years ago