====== Boost ======
===== Install =====
$ sudo apt-get install libboost-all-dev
When you do that you need to link the library with -l, the available libraries are:
* boost_system
* boost_timer
* boost_thread
===== Asio (networking) =====
==== UDP Server ====
#include
#include
#include
#include
using namespace boost::asio;
using namespace boost::posix_time;
io_service service;
void handle_connections() {
char buff[1024];
ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 8001));
while ( true) {
ip::udp::endpoint sender_ep;
int bytes = sock.receive_from(buffer(buff), sender_ep);
std::string msg(buff, bytes);
std::cout << "Received: " << msg << std::endl;
sock.send_to(buffer(msg), sender_ep);
}
}
int main(int argc, char* argv[]) {
handle_connections();
}
==== UDP Client ====
#include
#include
#include
#include
#include
using namespace boost::asio;
io_service service;
ip::udp::endpoint ep( ip::address::from_string("127.0.0.1"), 8001);
void sync_echo(std::string msg) {
ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 0) );
sock.send_to(buffer(msg), ep);
char buff[1024];
ip::udp::endpoint sender_ep;
int bytes = sock.receive_from(buffer(buff), sender_ep);
std::string copy(buff, bytes);
std::cout << "server echoed our " << msg << ": "
<< (copy == msg ? "OK" : "FAIL") << std::endl;
sock.close();
}
int main(int argc, char* argv[]) {
// connect several clients
char* messages[] = { "John says hi", "so does James", "Lucy just got home", 0 };
boost::thread_group threads;
for ( char ** message = messages; *message; ++message) {
threads.create_thread( boost::bind(sync_echo, *message));
boost::this_thread::sleep( boost::posix_time::millisec(100));
}
threads.join_all();
}