GodotTicTacToe/scripts/net/syncing/PacketDistributor.cs

87 lines
2.8 KiB
C#

using Godot;
using Network.PacketHandling;
using System.Collections.Generic;
using Util;
namespace Network.Syncing {
public class PacketDistributor {
private Peer Peer;
private List<ConnectionHandler> HandlerList = new List<ConnectionHandler>();
private int UnreliableIDCounter = 0;
private int ReliableIDCounter = 0;
private float TimeSinceLastSync = 0;
private readonly float Interval;
public PacketDistributor(Peer peer, float interval) {
Peer = peer;
Interval = interval;
}
public void Update(float delta) {
TimeSinceLastSync += delta;
if (TimeSinceLastSync > Interval) {
TimeSinceLastSync = 0;
foreach (ConnectionHandler Handler in HandlerList) {
Handler.SerializeAndSendQueues(UnreliableIDCounter++);
}
}
}
public void HandleRawPacket(PacketBuffer packetBuffer, Connection connection) {
var Handler = GetHandlerFor(connection);
if (Handler.isEmpty) {
Handler = new ConnectionHandler(Peer, connection);
HandlerList.Add(Handler);
}
Handler.Value.ReceiveBuffer(packetBuffer);
}
public void AddHandler(Connection connection) {
var Handler = new ConnectionHandler(Peer, connection);
HandlerList.Add(Handler);
}
public void AddReliableFor(Connection connection, Serializable serializable) {
var ConnHandlerOpt = GetHandlerFor(connection);
if (ConnHandlerOpt.HasValue) {
ConnHandlerOpt.Value.AddReliable(serializable, ReliableIDCounter++);
}
}
public void AddUnreliableFor(Connection connection, Serializable serializable) {
var ConnHandlerOpt = GetHandlerFor(connection);
if (ConnHandlerOpt.HasValue) {
ConnHandlerOpt.Value.AddUnreliable(serializable, UnreliableIDCounter++);
}
}
public void AddReliableForAll(Serializable serializable) {
foreach (ConnectionHandler Handler in HandlerList) {
Handler.AddReliable(serializable, ReliableIDCounter++);
}
}
public void AddUnreliableForAll(Serializable serializable) {
foreach (ConnectionHandler Handler in HandlerList) {
Handler.AddUnreliable(serializable, UnreliableIDCounter++);
}
}
private Optional<ConnectionHandler> GetHandlerFor(Connection connection) {
foreach (ConnectionHandler Curr in HandlerList) {
if (Curr.Connection == connection) {
return Curr;
}
}
return Optional<ConnectionHandler>.None;
}
}
}