Data Streaming
Sometimes it is necessary to send large amounts of data over the network, such as when synchronizing a player-built map. Neither Networked Properties nor Remote Procedure Calls (RPCs)—which should generally not be used to transmit large payloads—are well suited to this task, and that's where Fusion's data streaming API comes in.
The NetworkRunner
's SendReliableDataToPlayer
and SendReliableDataToServer
methods can be used to send large byte arrays:
C#
// Large data that needs to be sent
byte[] largeData = new byte [10000];
// Provide 4 numbers as a unique key for the data
var key = ReliableKey.FromInts(42, 0, 0, 0);
// Use in shared mode or as the server/host to send data to players
runner.SendReliableDataToPlayer(playerRef, key, largeData);
// Use as a client to send data to the server/host
runner.SendReliableDataToServer(key, largeData);
Under the hood, this data will be split into multiple fragments which are then streamed to the server/target client and reassembled.
Once the full data is received, the INetworkRunnerCallbacks.OnReliableDataReceived
callback is invoked. A separate callback is provided to track the status of the data transfer:
C#
public void OnReliableDataReceived(NetworkRunner runner, PlayerRef player, ReliableKey key, ArraySegment<byte> data) { }
public void OnReliableDataProgress(NetworkRunner runner, PlayerRef player, ReliableKey key, float progress) { }
It's possible to stream multiple sets of data in parallel, and each one is identified by a key
consisting of 16 bytes (created from four int
s or two ulong
s).
The key
can also be used to transmit metadata, such as which object should be responsible for processing the data on the receiving end. This may be necessary if multiple classes implement the OnReliableDataReceived
callback with each one only being interested in a subset of the types of data which are received.