Created
January 5, 2016 06:21
-
-
Save yueyoum/3cbb3b51e7306c7abf1f to your computer and use it in GitHub Desktop.
how to set SO_REUSEPORT flat with boost asio library
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
#include <iostream> | |
#include <string> | |
#include <array> | |
#include <boost/asio.hpp> | |
#include <arpa/inet.h> | |
using boost::asio::ip::tcp; | |
int main() | |
{ | |
boost::asio::io_service io; | |
tcp::acceptor acceptor(io); | |
acceptor.open(tcp::v4()); | |
int one = 1; | |
setsockopt(acceptor.native_handle(), SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &one, sizeof(one)); | |
acceptor.bind(tcp::endpoint(tcp::v4(), 9091)); | |
acceptor.listen(); | |
std::cout << "start" << std::endl; | |
for(;;) | |
{ | |
tcp::socket socket(io); | |
acceptor.accept(socket); | |
std::cout << "new connections" << std::endl; | |
for(;;) | |
{ | |
std::array<char, 4> buf; | |
boost::system::error_code error; | |
boost::asio::read(socket, boost::asio::buffer(buf), error); | |
if(error) | |
{ | |
std::cout << "read error: " << error << std::endl; | |
break; | |
} | |
std::cout << "read: " << std::string(buf.data()) << std::endl; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment