Network rookie question

Hello.
I'm trying to write my first code using boost::asio.

My first step would be to ensure that I can accept incoming TCP, for this I wrote a simple program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//============================================================================
// 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>

using namespace std;
using namespace 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.
			}
			else if (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...

Why is that?
What am I doing wrong?
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();
Topic archived. No new replies allowed.