2017-11-25 11:26:55 +01:00
|
|
|
|
|
2017-11-25 14:21:06 +01:00
|
|
|
|
using Godot;
|
|
|
|
|
using Network.PacketHandling.Packets;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using Util;
|
|
|
|
|
|
2017-11-25 11:26:55 +01:00
|
|
|
|
namespace Network.PacketHandling {
|
|
|
|
|
public class Protocol {
|
|
|
|
|
|
2017-11-25 14:21:06 +01:00
|
|
|
|
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;
|
|
|
|
|
|
2017-11-25 11:26:55 +01:00
|
|
|
|
private Peer Peer;
|
|
|
|
|
|
|
|
|
|
public Protocol(Peer peer) {
|
|
|
|
|
Peer = peer;
|
2017-11-25 14:21:06 +01:00
|
|
|
|
|
|
|
|
|
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);
|
2017-11-25 11:26:55 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|