Files
BoneSync/BoneSync/Networking/Transport/SteamTransport.cs
2025-02-25 07:07:16 +02:00

66 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BoneSync.Networking.LobbyManager;
using Facepunch.Steamworks;
using Facepunch.Steamworks.Data;
namespace BoneSync.Networking.Transport
{
internal class SteamTransport : TransportBase
{
SteamLobbyManager _instance;
public override event Action<Packet> OnReceive;
public SteamTransport(SteamLobbyManager lobbyManager)
{
SteamNetworking.OnP2PSessionRequest += OnP2PSessionRequest;
}
private void OnP2PSessionRequest(SteamId steamId)
{
SteamNetworking.AcceptP2PSessionWithUser(steamId);
}
private void ProcessPacket(P2Packet steamPacket)
{
Packet packet = Packet.FromBytes(steamPacket.Data);
bool isTarget = packet.Info.receiverId == 0 || packet.Info.receiverId == _instance.GetLocalId();
if (isTarget)
{
OnReceive?.Invoke(packet);
}
}
public override bool Tick()
{
while (SteamNetworking.IsP2PPacketAvailable())
{
P2Packet packet = (P2Packet)SteamNetworking.ReadP2PPacket();
ProcessPacket(packet);
}
return true;
}
public override void Send(Packet packet)
{
if (packet.Info.receiverId == 0)
{
foreach (SteamId peer in _instance.Peers)
{
byte[] packetBytes = packet.ToBytes();
SteamNetworking.SendP2PPacket(peer, packetBytes, packetBytes.Length, 0, P2PSend.Reliable);
}
return;
}
else
{
SteamId peer = (SteamId)_instance.getPeerFromId(packet.Info.receiverId);
SteamNetworking.SendP2PPacket(peer, packet.ToBytes(), packet.ToBytes().Length, 0, P2PSend.Reliable);
}
}
}
}