quakeball/Assets/Scripts/Net/Packets/Protocol.cs

67 lines
2.4 KiB
C#
Raw Normal View History

2020-08-05 03:21:04 +02:00
using System.Collections.Generic;
using System;
using NeonTea.Quakeball.Net.Peers;
namespace NeonTea.Quakeball.Net.Packets {
public abstract class Protocol {
private Dictionary<Type, int> PacketToId = new Dictionary<Type, int>();
private Dictionary<int, Type> IdToPacket = new Dictionary<int, Type>();
private int PacketIdCounter;
public Peer Peer;
public abstract byte Identifier { get; }
public abstract string Version { get; }
public abstract void Receive(Connection conn, Packet packet);
public abstract void ConnectionStatusChanged(ConnectionStatus oldStatus, ConnectionStatus newStatus, Connection conn);
public abstract void Timeout(Connection conn);
public void SendPacket(Packet p, Connection conn) {
Peer.ConnectionManager.AddPacketToQueue(conn, p);
Peer.ConnectionManager.SendPacketQueue(conn);
}
public int RegisterPacket(Type t) {
if (t.BaseType != typeof(Packet) || PacketToId.ContainsKey(t)) {
return -1;
}
int id = PacketIdCounter++;
PacketToId.Add(t, id);
IdToPacket.Add(id, t);
return id;
}
public ByteBuffer BuildMessage(Connection connection) {
ByteBuffer buffer = new ByteBuffer();
foreach (byte b in Peer.Fingerprint) {
buffer.Write(b);
}
buffer.Write(Identifier);
if (connection.Status == ConnectionStatus.Establishing) {
Peer.MessageListener.Message("Sending Establishing");
buffer.Write((byte)PacketStage.Establishing);
buffer.WriteString(Version);
} else if (connection.Status == ConnectionStatus.Closed) {
buffer.Write((byte)PacketStage.Closed);
} else if (connection.Status == ConnectionStatus.Rejected) {
buffer.Write((byte)PacketStage.Rejected);
buffer.Write((byte)connection.ClosingReason);
} else if (connection.Status == ConnectionStatus.Ready) {
buffer.Write((byte)PacketStage.Ready);
buffer.WriteInt(connection.LatestPacketReceived);
}
return buffer;
}
public int GetPacketID(Packet packet) {
return PacketToId[packet.GetType()];
}
public Type GetPacketType(int id) {
return IdToPacket[id];
}
}
}