From 72c37b5c7a47c8380a9dc0e76e08e41ab0086ccb Mon Sep 17 00:00:00 2001 From: Timothy Schenk Date: Fri, 11 Aug 2023 01:18:11 +0200 Subject: [PATCH] feat: implement IPacket based Send function --- Server/AuthSession.cs | 44 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/Server/AuthSession.cs b/Server/AuthSession.cs index d6c88e2..9a591b7 100644 --- a/Server/AuthSession.cs +++ b/Server/AuthSession.cs @@ -1,8 +1,11 @@ -using System.Text; +using System.Diagnostics; +using System.Reflection; +using System.Text; using MassTransit.Mediator; using Microsoft.Extensions.Logging; using NetCoreServer; using Server.Packets; +using Buffer = System.Buffer; namespace Server; @@ -18,6 +21,45 @@ public class AuthSession : TcpSession _logger = logger; } + public override long Send(byte[] buffer) + { + _logger.LogInformation("Data being sent is: {Data}", BitConverter.ToString(buffer)); + return base.Send(buffer); + } + + public void Send(IPacket packet) + { + var type = packet.GetType(); + _logger.LogTrace("Packet of type {Type} is being serialized", type.Name); + var packetIdAttribute = type.GetCustomAttribute(); + if (packetIdAttribute == null) return; + var opcode = packetIdAttribute.Code; + + Span packetData = packet.Serialize(); + ushort length = (ushort)(packetData.Length + 8); + + Span buffer = stackalloc byte[length]; + buffer.Clear(); + packetData.CopyTo(buffer.Slice(8, length - 8)); + + var bytesOfLength = BitConverter.GetBytes(length); + var bytesOfOpcode = BitConverter.GetBytes((ushort)opcode); + for (int i = 0; i < bytesOfLength.Length || i < 2; i++) + { + buffer[i] = bytesOfLength[i]; + } + + for (int i = 0; i < bytesOfOpcode.Length || i < 2; i++) + { + buffer[2 + i] = bytesOfOpcode[i]; + } + + _logger.LogTrace("Packet data being parsed is: {Data}", BitConverter.ToString(packetData.ToArray())); + _logger.LogTrace("Packet being parsed is: {Data}", BitConverter.ToString(buffer.ToArray())); + + Send(buffer); + } + protected override void OnReceived(byte[] buffer, long offset, long size) { Console.WriteLine($"Length: {size} & offset: {offset}");