Skip to content

Instantly share code, notes, and snippets.

@askdaddy
Created September 29, 2020 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save askdaddy/f85ee9c41c26c3cb30045d3d36d9d2a6 to your computer and use it in GitHub Desktop.
Save askdaddy/f85ee9c41c26c3cb30045d3d36d9d2a6 to your computer and use it in GitHub Desktop.
sending-protobuf-messages-with-boostasio
#include "boost/asio.hpp"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
// https://stackoverflow.com/questions/4810026/sending-protobuf-messages-with-boostasio
using ::boost::asio::ip::udp;
int main() {
PlayerInfo message;
message.set_name("Player 1");
// ...
const boost::asio::ip::address_v4 kIpAddress = boost::asio::ip::address_v4::loopback();
const unsigned short kPortNumber = 65535;
try {
boost::asio::io_service io_service;
udp::socket socket(io_service, boost::asio::ip::udp::v4());
udp::endpoint endpoint(kIpAddress, kPortNumber);
boost::system::error_code error;
boost::asio::streambuf stream_buffer;
std::ostream output_stream(&stream_buffer);
{
::google::protobuf::io::OstreamOutputStream raw_output_stream(&output_stream);
::google::protobuf::io::CodedOutputStream coded_output_stream(&raw_output_stream);
coded_output_stream.WriteVarint32(message.ByteSize());
message.SerializeToCodedStream(&coded_output_stream);
// IMPORTANT: In order to flush a CodedOutputStream it has to be deleted,
// otherwise a 0 bytes package is send over the wire.
}
}
size_t len = socket.send_to(stream_buffer.data(), endpoint, 0, error);
if (error && error != boost::asio::error::message_size) {
throw boost::system::system_error(error);
}
std::cout << "Sent " << len << " bytes data to " << kIpAddress.to_string() << "." << std::endl;
} catch (const std::exception& ex) {
std::cerr << ex.what() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment