检查basic_socket_acceptor是否准备好接受(Check if basic_socket_acceptor is ready to accept)
我正在使用Networking TS编写一个简单的单线程TCP服务器。 为了接受传入连接,我创建了std::experimental::net::ip::tcp::acceptor并调用accept成员函数。 但是如果没有连接可以接受,我就不会这么做。 如何检查接受器是否已准备好接受?
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?
最满意答案
显然,如果有一个函数最终会调用select ,它会暴露竞争条件 。 正确的方法是将acceptor设置为非阻塞。
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 }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 }更多推荐
发布评论