Receiving serialized custom message types over a network, how to cast?
I'm writing a networked application.
Assume a class called Packet. This class has some public properties.
public class Packet
{
public Module DestinationModule { get; set; }
public EncryptionCompressionFlag EncryptedOrCompressed { get; set; }
public PacketPriority Priority { get; set; }
public Origin Origin { get; set; }
// You'll see why I need this later
// This StackOverflow question is asking how I can do without this property
public Type UltimateType { get; set; }
}
Now assume a class called LoginPacket. This class extends Packet, and includes even more properties.
public class LoginPacket : Packet
{
public string Username { get; set; }
public string Password { get; set; }
}
But LoginPacket is not the only type of custom packet. There are many more custom packets.
My client application is constantly serializing custom packets and sending them over the wire. When they are deserialized on the other side, however, I can only deserialize them as a Packet, not as a specific LoginPacket.
Question: How can I 开发者_如何学JAVAknow the 'ultimate' or 'original' specific type of the Packet? Per the example, the specific type would have been LoginPacket. I don't know the specific type because I receive it over the wire simply as a Packet and without a "type" property (like UltimateType, which sounds lame), I don't know how to discover the specific original type.
Response: "How do you serialize the packet?"
I use YAXSerializer. I tested a specific serialization and deserialization of LoginPacket, and it was successful. I was able to deserialize the string (YAX serializes to a string, not byte array, difference doesn't really matter..) into a Packet and a LoginPacket.
public static string SerializePacket(Packet packet)
{
YAXSerializer serializer = new YAXSerializer(packet.UltimateType);
return serializer.Serialize(packet);
}
According to the YAXSerializer docs, the opening XML element for each class is the class name... so each LoginPacket in your string should look like...
<LoginPacket ...>
....
</LoginPacket>
Just parse the string yourself and look for the class name, if you don't want to put it in a property of the 'Packet' class.
精彩评论