HomeGuidesAPI Reference
HubBlogChangelogSupport ForumLog In
Guides

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('Messages', RainwayChannelMode.Reliable);

The peer that accepted the connection request then gets an onPeerDataChannel event for each created channel.

Rainway.initialize({
    onPeerDataChannel: (runtime, peer, channel, mode) => {
        console.log(`New data channel '${channel}' create by remote peer ${peer}`);
    }
    // additional config entries
})

Sending and receiving messages

To send a message to a Peer, use the send method on RainwayPeer:

peer.send("Messages", new Uint8Array([1, 2, 3]));

Messages from the remote Peer are received by the OnPeerMessage handler:

Runtime.initialize({
    onPeerMessage: (runtime, peer, channel, message) => {
        const name = peer.externalId;
        console.log(`Got a message from ${name}: ${message}`);
    }
    // additional config entries
})