I heard that sending packets in bytes is faster. So as my title ask, how do you convert a packet to bytes and back? I'm using the
enet network library to make my game utilize both TCP and UDP. I plan on packing everything I need into a sf::Packet and converting that into bytes then sending that.
// Server
sf::Packet packet = bleh;
bleh << variables;
bleh << positions; // Loading the packet up with stuff..
ENetPacket * packet = enet_packet_create (bleh.getData(), bleh.getDataSize() + 1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send (peer, 0, packet);
// Client
sf::Packet packet;
packet.append(event.packet->data, event.packet->dataLength);
Is that at all near close? If you're confused about the context of the variables, check the enet library I linked to above. I've also provided a UNFINISHED server-sided spoiler of some code if it helps:
void enetThread()
{
ENetEvent event;
/* Wait up to 1000 milliseconds for an event. */
while (enet_host_service (client, & event, 1000) > 0)
{
switch (event.type)
{
case ENET_EVENT_TYPE_CONNECT:
Connector* newConnector = new Connector();
newConnector->player = NULL;
newConnector.peer = event.peer;
newConnector->setID(sessionID);
sessionID++;
connectors.push_back(newConnector);
// Don't forget to check the clients revision.
std::cout << green << "\nNew connection accepted!" << basic << std::endl;
break;
case ENET_EVENT_TYPE_RECEIVE:
sf::Packet = event.packet->data;
handlePacket(getConnectorByPeer(ENetPeer event.peer), event.packet->data);
printf("A packet of length %u containing %s was received from %s on channel %u.\n",
event.packet -> dataLength,
event.packet -> data,
event.peer -> data,
event.channelID);
/* Clean up the packet now that we're done using it. */
enet_packet_destroy (event.packet);
break;
case ENET_EVENT_TYPE_DISCONNECT:
printf ("%s disconnected.\n", event.peer -> data);
/* Reset the peer's client information. */
event.peer -> data = NULL;
break;
}
}
}