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.CreateDataChannelAsync(new DataChannelOptions() { Id = "Messages", Mode = DataChannelMode.Reliable });

The peer that accepted the connection request then gets a DataChannel event for each created channel.

// add an event handler, that takes the sender (peer, in this case) and the event
peer.DataChannel += (sender, ev) => {
  // obtain the data channel
  var channel = ev.Data;
};

Sending and receiving messages

To send a message to a DataChannel, use the Send method:

channel.Send("hello world");

Messages from the remote peer are received by the Message event:

// add an event handler, that takes the sender (channel, in this case) and the event
channel.Message += (sender, ev) => {
  // byte[] data, composing the message
  var data = ev.Data;
  
  // same data, interpreted as a utf-8 string
  var str = ev.AsString;
};

Did this page help you?