64 lines
2.2 KiB
C#
64 lines
2.2 KiB
C#
|
|
using Godot;
|
|
using Network.PacketHandling.Packets;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using Util;
|
|
|
|
namespace Network.PacketHandling {
|
|
public class Protocol {
|
|
|
|
private static List<Type> RegisteredPacketTypes = new List<Type>();
|
|
private static int TypeCounter = 0;
|
|
|
|
private const int SYNC_PKT = 0;
|
|
private const int TEXT_MSG_PKT = 1;
|
|
|
|
private Peer Peer;
|
|
|
|
public Protocol(Peer peer) {
|
|
Peer = peer;
|
|
|
|
RegisterPacketType(SYNC_PKT, typeof(SyncPkt));
|
|
RegisterPacketType(TEXT_MSG_PKT, typeof(TextMessagePkt));
|
|
}
|
|
|
|
public static int GetPacketTypeIDFor(Serializable serializable) {
|
|
for (int i = 0; i < RegisteredPacketTypes.Count; i++) {
|
|
if (RegisteredPacketTypes[i] == serializable.GetType()) {
|
|
return i;
|
|
}
|
|
}
|
|
throw new InvalidOperationException("The serializable is not a registered packet type.");
|
|
}
|
|
|
|
public Serializable DeserializePacket(PacketBuffer packetBuffer, SerializableMetadata metadata) {
|
|
switch (metadata.PacketType) {
|
|
case SYNC_PKT: {
|
|
var SyncPkt = new SyncPkt();
|
|
SyncPkt.DeserializeWithMetadata(metadata, packetBuffer);
|
|
return SyncPkt;
|
|
}
|
|
case TEXT_MSG_PKT: {
|
|
var TextMessagePkt = new TextMessagePkt();
|
|
TextMessagePkt.DeserializeWithMetadata(metadata, packetBuffer);
|
|
return TextMessagePkt;
|
|
}
|
|
}
|
|
throw new InvalidOperationException("PacketType " + metadata.PacketType + " not registered.");
|
|
}
|
|
|
|
public void HandleSerializable(Serializable serializable) {
|
|
if (serializable.Metadata.PacketType == TEXT_MSG_PKT) {
|
|
var TMP = (TextMessagePkt) serializable;
|
|
GD.print("Received " + (TMP.Metadata.Reliable ? "Reliable" : "Unreliable") + " text message: " + TMP.Text);
|
|
}
|
|
}
|
|
|
|
private static void RegisterPacketType(int id, Type type) {
|
|
RegisteredPacketTypes.Insert(id, type);
|
|
}
|
|
|
|
}
|
|
}
|