Manager Initializer initializes all managers found inheriting the IManager interface Packet Manager - Created LoadPacketInfo which gets PropertyInfo using reflection, and caches the returned information - Started on Send<Packet>(Packet) - Started on serializing packets to stream - Started on packet deserializer Created PacketIgnore attribute to ignore properties in a packet when serializing
87 lines
2.5 KiB
C#
87 lines
2.5 KiB
C#
using Articulate_Network.Attributes;
|
|
using Articulate_Network.Interfaces;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Articulate_Network.Managers
|
|
{
|
|
public class PacketManager : IManager
|
|
{
|
|
Dictionary<Type, List<PropertyInfo>> packetInfo = new Dictionary<Type, List<PropertyInfo>>();
|
|
|
|
public void Initialize()
|
|
{
|
|
|
|
}
|
|
|
|
public void LoadPacketInfo(IPacket packet)
|
|
{
|
|
packetInfo.Add(packet.GetType(), packet.GetType().GetProperties().Where(f => !Attribute.IsDefined(f, typeof(PacketIgnore))).OrderBy(f => f.Name).ToList());
|
|
}
|
|
|
|
public T Send<T>(IPacket packet)
|
|
{
|
|
if (!packetInfo.ContainsKey(packet.GetType()))
|
|
LoadPacketInfo(packet);
|
|
|
|
|
|
//send packet
|
|
|
|
var serialized = SerializePacket(packet);
|
|
|
|
var deserialized = DeserializePacket<T>(serialized);
|
|
|
|
return (T)deserialized;
|
|
}
|
|
|
|
public MemoryStream SerializePacket(IPacket packet)
|
|
{
|
|
var fields = packetInfo[packet.GetType()];
|
|
|
|
MemoryStream memoryStream = new MemoryStream();
|
|
BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
|
|
|
|
foreach (var field in fields)
|
|
{
|
|
if (field.PropertyType == typeof(bool))
|
|
binaryWriter.Write((bool)field.GetValue(packet));
|
|
|
|
if (field.PropertyType == typeof(int))
|
|
binaryWriter.Write((int)field.GetValue(packet));
|
|
|
|
if (field.PropertyType == typeof(string))
|
|
binaryWriter.Write((string)field.GetValue(packet));
|
|
}
|
|
|
|
return memoryStream;
|
|
}
|
|
|
|
public T DeserializePacket<T>(Stream stream)
|
|
{
|
|
IPacket packet = (IPacket)Activator.CreateInstance(typeof(T));
|
|
|
|
var fields = packetInfo[typeof(T)];
|
|
BinaryReader reader = new BinaryReader(stream);
|
|
|
|
foreach (var field in fields)
|
|
{
|
|
if (field.PropertyType == typeof(bool))
|
|
field.SetValue(packet, reader.ReadBoolean());
|
|
|
|
if (field.PropertyType == typeof(int))
|
|
field.SetValue(packet, reader.ReadInt32());
|
|
|
|
if (field.PropertyType == typeof(string))
|
|
field.SetValue(packet, reader.ReadString());
|
|
}
|
|
|
|
return (T)packet;
|
|
}
|
|
}
|
|
}
|