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.

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

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]));

The message will be received by the onPeerMessage handler configured in RainwayRuntime on the other end.

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

Did this page help you?