I'm trying to determine the best way to transfer a c# type across the network so when it gets to the other side, I can serialize it.
Right now, I am doing this
public void Send<T>(T packet) {
NetworkStream Stream = Server.GetStream();
byte[] typeName = Encoding.UTF8.GetBytes(typeof(T).FullName);
byte[] typeLength = BitConverter.GetBytes(typeName.Length);
byte[] packetdata = Encoding.UTF8.GetBytes(JsonSerializer.Serialize<T>(packet));
byte[] length = BitConverter.GetBytes(packetdata.Length);
Stream.Write(typeLength, 0, 4);
Stream.Write(typeName, 0, typeName.Length);
Stream.Write(length, 0, 4);
Stream.Write(packetdata, 0, packetdata.Length);
}
On the other end I want to do something like this
byte[] BufferedData = new byte[0];
while (Alive) {
byte[] StreamData = new byte[1024];
int bytesRead = Client.tcpClient.GetStream().Read(StreamData, 0, StreamData.Length); // Read data off the network
BufferedData = BufferedData.Join(StreamData.Sub(0, bytesRead)); // Pull the recieved data out and buffer it
// [TypeLength, TypeName, DataLength, Data]
if (BufferedData.Length > 4) { // If the packet length data has been received
int typeLength = BitConverter.ToInt32(BufferedData); // Gets the first 4 bytes off the data and puts it into the data length int
if (BufferedData.Length >= typeLength + 8) { // If the type and the data length of the packet has been received
int dataLength = BitConverter.ToInt32(BufferedData.Sub(typeLength + 4, 4)); // Get the data length off the packet
if (BufferedData.Length >= typeLength + dataLength + 8) { // If the whole packet has been received
string data = Encoding.UTF8.GetString(BufferedData.Sub(typeLength + 8, dataLength)); // Get the data as a string
Type x = Type.GetType(Encoding.UTF8.GetString(BufferedData.Sub(4, typeLength))); // Get the type of the data
-> x obj = (x)JsonSerializer.Deserialize<x>(data); // This is what i need to figure out
onReceived.Invoke(JsonSerializer.Deserialize<IMistoxPacket>(Encoding.UTF8.GetString(BufferedData.Sub(4, dataLength))), new EventArgs()); // Split out packet and send it up
BufferedData = BufferedData.Sub(dataLength, BufferedData.Length - dataLength); // Remove the packet from the Buffered data
}
}
}
}
How do i get x to be the type of x instead. so the obj can be the type of x. if that makes since
I don't know if this is a viable path or if there is a better way of doing something like this. I want to send multiple packet types across the same code and split them out later. Any help would be awesome.