I'm writing a simple single threaded TCP server using Networking TS. In order to accept incoming connections, I create std::experimental::net::ip::tcp::acceptor
and call accept
member function. But it blocks if there is no connection to accept and I don't want that. How can I check if acceptor is ready to accept?
Asked
Active
Viewed 306 times
0
-
1I am not used to play with experimental features, but in good old socket API, one can use select to know whether a listening socket has a pending connection. The experimental C++ API has probably a method for that. – Serge Ballesta Dec 14 '17 at 13:19
-
I'm guessing the APIs you're using are based on [boost::asio](http://www.boost.org/doc/libs/1_65_0/doc/html/boost_asio/reference.html)? If so I'd expect there to be an [asynchronous version of `accept`](http://www.boost.org/doc/libs/1_65_0/doc/html/boost_asio/reference/basic_socket_acceptor/async_accept.html) as well. – G.M. Dec 14 '17 at 14:05
-
@SergeBallesta Yes, I'm aware of that. – Dec 14 '17 at 20:19
-
@G.M. But wouldn't that need a separate thread to wait for new connection? I want to keep stuff as simple as possible and use only one thread. – Dec 14 '17 at 20:20
-
1Not necessarily. The underlying implementation more than likely makes use of the `select` system call (as hinted at by @SergeBallesta). Can you provide more information about exactly what it is you're trying to achieve. Or, better still, provide a [mcve] that replicates the problem. – G.M. Dec 14 '17 at 21:40
-
@G.M. I'm just writing a hello world server that will do some work while waiting for incoming connections. Basically, calling `DoStuff()` and imaginary `can_accept()` in loop. – Dec 14 '17 at 22:39
1 Answers
1
Apparently, if there would be a function that would ultimately call select
, it would expose a race condition. The correct way is to set acceptor to be non-blocking.
std::experimental::net::io_context context;
std::experimental::net::ip::tcp::acceptor acceptor{context,
std::experimental::net::ip::tcp::endpoint{
std::experimental::net::ip::tcp::v4(), 1234}};
acceptor.non_blocking(true);
std::error_code error;
while (true)
{
auto socket = acceptor.accept(error);
if (!error)
{
// Handle incoming connection
}
// Do other stuff
}