//============================================================================
// Name : boost_network.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <thread>
#include <exception>
#include <boost/asio.hpp>
#include <boost/array.hpp>
usingnamespace std;
usingnamespace boost;
void accept_handler(asio::ip::tcp::socket socket)
{
try {
for (;;)
{
char data[2000];
boost::system::error_code error;
size_t length = socket.read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof) {
break; // Connection closed cleanly by peer.
}
elseif (error)
throw boost::system::system_error(error); // Some other error.
cout << "Request: " << length << " bytes." << endl;
}
} catch (std::exception& e) {
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
int main() {
int port_num = 3333;
auto tcp_endpoint = asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port_num);
asio::io_service io;
auto tcp_acceptor = asio::ip::tcp::acceptor(io, tcp_endpoint);
tcp_acceptor.listen();
for(int i=0; i<3; i++) {
asio::ip::tcp::socket tcp_socket(io);
tcp_acceptor.accept(tcp_socket);
thread(accept_handler, move(tcp_socket)).detach();
}
tcp_acceptor.close();
return 0;
}
The code is very much based on the boost "blocking tcp echo server" example.
My idea is that the code above, when accessed from a web browser at localhost:3333 would give one printout for each time I (re)load the URL.
I also expected exactly 3 printouts.
However, I do not always get exactly 3 printouts. Sometimes it's just 2, sometimes it's 4...
Note that you are detaching the created thread. That means that the OS is not required to wait for that thread to finish before shutting down the entire process.
If you want to wait for all processes to finish before main() can return, you can do
1 2 3 4 5 6
std::vector<std::thread> threads;
//in the loop:
threads.emplace_back(accept_handler, std::move(tcp_socket));
//after the loop:
for (auto &t : threads)
t.join();