Estoy tratando de determinar la mejor manera de transferir el tipo ac# a través de la red para que cuando llegue al otro lado, pueda serializarlo.
Ahora mismo, estoy haciendo esto
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); }En el otro extremo quiero hacer algo como esto.
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 } } } }¿Cómo consigo que x sea el tipo de x en su lugar? por lo que el obj puede ser el tipo de x. si eso hace desde
No sé si este es un camino viable o si hay una mejor manera de hacer algo como esto. Quiero enviar varios tipos de paquetes a través del mismo código y dividirlos más tarde. Cualquier ayuda sería increíble.