I was going to post here
http://en.sfml-dev.org/forums/index.php?topic=3172.0, but it's too old so I thought I'd start a new topic.
Basically the original poster wanted to check the type of packet he sent before he opened it on the receiving end, and his idea was to put a header at the beginning of each packet to correctly identify how to proceed with opening it and storing it correctly.
Laurent replied with this code for the sender and receiver.
Sending:// sending
sf::Packet packet;
packet << header << ... specific data ... ;
socket.Send(packet);
Receiving:// receiving
sf::Packet packet;
socket.Receive(packet);
sf::Uint8 header;
packet >> header;
switch (header)
{
case ConnectionRequest:
packet >> ... specific data ...;
connect(...);
break;
case MoveObject:
packet >> ... specific data ...;
moveObject(...);
break;
...
}
I think this is a great idea, but I wanted to make sure with you guys if you all think it's the right way to do this before I start.
Also, on the receiving side, inside the switch, each case has:
packet >> ...specific data...;
I'm wondering if that"specific data" could be a user type?
For example:
struct Character
{
sf::Uint8 age;
std::string name;
float height;
};
sf::Packet& operator <<(sf::Packet& packet, const Character& character)
{
return packet << character.age << character.name << character.height;
}
sf::Packet& operator >>(sf::Packet& packet, Character& character)
{
return packet >> character.age >> character.name >> character.height;
}
struct Enemy
{
sf::Uint16 health;
sf::Uint16 power;
sf::Uint8 type;
};
sf::Packet& operator <<(sf::Packet& packet, const Enemy& enemy)
{
return packet << enemy.health << enemy.power << enemy.type;
}
sf::Packet& operator >>(sf::Packet& packet, Enemy& enemy)
{
return packet >> enemy.health >> enemy.power >> enemy.type;
}
// receiving
sf::Packet packet;
socket.Receive(packet);
sf::Uint8 header;
packet >> header;
switch (header)
{
case isCharacter:
Character billy;
packet >> billy;
break;
case isEnemy:
Enemy boss;
packet >> boss;
break;
...
}
I guess what I'm asking is if the header value could be separate from the user type?