Created
May 12, 2015 05:23
-
-
Save yxbh/dfecc4cd44990440b5e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
char buffer[2048]; // our packet buffer | |
// | |
// say we have the following variables that we need to pack into our packet. | |
// | |
std::uint16_t ptype = 101u; | |
bool success = true; | |
char str[] "hello world."; | |
// | |
// we pack them into the packet buffer here. | |
// | |
char * p = buffer; // get a pointer and use it as a cursor into the buffer. we start at the beginning of the buffer here. | |
std::memset(buffer, 0, sizeof buffer); // 0 the buffer. good habit. | |
// pack the ptype | |
std::uint16_t ptype_in_networkorder = htons(ptype); // convert integer to network order. | |
std::memcpy(p, &ptype_in_networkorder, sizeof ptype); | |
p += sizeof ptype; // increment our cursor. | |
// pack the bool flag | |
std::memcpy(p, &success, sizeof success); | |
p += sizeof success; | |
// pack the string. in this case we will pack the len too. | |
std::uint32_t len = htonl(strlen(str)); | |
std::memcpy(p, &len, sizeof len); | |
p += sizeof len; // increment our cursor. | |
std::memcpy(p, str, strlen(str)); | |
p += strlen(str); | |
// | |
// send off the packet | |
// | |
std::size_t packet_size = p - buffer; | |
::send(socket_fd, buffer, packet_size); | |
// | |
// Alternativelly if you use my packet class. | |
// this is how I do it in my code. | |
// | |
Packet p; | |
p << ptype << success << str; // everything is abstracted for me. | |
::send(socket_fd, p.getData(), p.getSize()); | |
p.clear(); // ready for reuse. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment