如何在 boost asio 中设置阻塞套接字超时?

How to set a timeout on blocking sockets in boost asio?(如何在 boost asio 中设置阻塞套接字超时?)
本文介绍了如何在 boost asio 中设置阻塞套接字超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有没有办法取消挂起的操作(无需断开连接)或为 boost 库函数设置超时?

Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?

即我想在 boost asio 中设置阻塞套接字超时?

I.e. I want to set a timeout on blocking socket in boost asio?

socket.read_some(boost::asio::buffer(pData, maxSize), error_);

socket.read_some(boost::asio::buffer(pData, maxSize), error_);

示例:我想从套接字中读取一些内容,但如果 10 秒过去了,我想抛出一个错误.

Example: I want to read some from the socket, but I want to throw an error if 10 seconds have passed.

推荐答案

在 Linux/BSD 下,操作系统直接支持套接字上的 I/O 操作超时.该选项可以通过 setsocktopt() 启用.我不知道 boost::asio 是否提供设置它的方法或公开套接字脚本以允许您直接设置它——后一种情况并不是真正可移植的.

Under Linux/BSD the timeout on I/O operations on sockets is directly supported by the operating system. The option can be enabled via setsocktopt(). I don't know if boost::asio provides a method for setting it or exposes the socket scriptor to allow you to directly set it -- the latter case is not really portable.

为了完整起见,这里是手册页中的描述:

For a sake of completeness here's the description from the man page:

SO_RCVTIMEOSO_SNDTIMEO

          Specify the receiving or sending  timeouts  until  reporting  an
          error.  The argument is a struct timeval.  If an input or output
          function blocks for this period of time, and data has been  sent
          or  received,  the  return  value  of  that function will be the
          amount of data transferred; if no data has been transferred  and
          the  timeout has been reached then -1 is returned with errno set
          to EAGAIN or EWOULDBLOCK just as if the socket was specified  to
          be  non-blocking.   If  the timeout is set to zero (the default)
          then the operation  will  never  timeout.   Timeouts  only  have
          effect  for system calls that perform socket I/O (e.g., read(2),
          recvmsg(2), send(2), sendmsg(2)); timeouts have  no  effect  for
          select(2), poll(2), epoll_wait(2), etc.

这篇关于如何在 boost asio 中设置阻塞套接字超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)