Revision Difference
Sending_P2P_Messages#524751
<cat>code.networking</cat>⤶
<title>P2P Networking</title>⤶
⤶
Steam has a mechanism allowing you to send packets to another Steam user. ⤶
⤶
It's totally feasible to create a game's netcode using this system.⤶
⤶
<note>In the past we used this in Rust to send voice communications instead of bouncing it off the server. We ultimately stopped doing this because it revealed your IP.</note>⤶
⤶
# Sending Messages⤶
⤶
```⤶
byte[] mydata = ...⤶
SteamId TargetSteamId = ...⤶
⤶
var sent = SteamNetworking.SendP2PPacket( TargetSteamId, mydata );⤶
⤶
// if sent is true - the data was sent !⤶
⤶
```⤶
⤶
⤶
# Receiving Messages⤶
⤶
You need to set up a callback so you can authorize who can send you messages⤶
⤶
```⤶
SteamNetworking.OnP2PSessionRequest = ( steamid ) =>⤶
{⤶
// If we want to let this steamid talk to us⤶
SteamNetworking.AcceptP2PSessionWithUser( steamid );⤶
}⤶
⤶
```⤶
⤶
Then just call something like this regularly⤶
⤶
```⤶
while ( SteamNetworking.IsP2PPacketAvailable() )⤶
{⤶
var packet = SteamNetworking.ReadP2PPacket();⤶
if ( packet.HasValue )⤶
{⤶
HandleMessageFrom( packet.Value.SteamId, packet.Value.Data );⤶
}⤶
}⤶
```⤶
⤶
Your HandleMessageFrom function should look like this⤶
⤶
```⤶
void HandleMessageFrom( SteamId steamid, Data data )⤶
{⤶
.. do stuff⤶
}⤶
```⤶
⤶
# Further Reading⤶
⤶
There are less garbage creating versions of some of the functions here on the <page>SteamNetworking</page> class.⤶
⤶
Although the p2p stuff is easy and will work out for a lot of situations, you should look at <page>SteamNetworkingSockets</page> if you're planning to make a game with client/server architecture with 10+ players sending updates multiple times a second.⤶