检查basic

编程入门 行业动态 更新时间:2024-10-25 20:19:04
检查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 }

更多推荐

本文发布于:2023-08-06 21:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:basic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!