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", reliable: true);

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

var config = new RainwayConfig {
    OnPeerDataChannel: (runtime, peer, channelName, mode) => {
        Console.WriteLine($"New data channel {channelName} 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", "string that will be UTF-8 encoded");
peer.Send("Messages", new byte[] { 1, 2, 3 });

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

var config = new RainwayConfig {
    OnPeerMessage: (runtime, peer, channelName, message) => {
        Console.WriteLine($"Got a message from {peer.ExternalId}: {message}");
    }
    // additional config entries
}