basic_stream_descriptor.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. //
  2. // posix/basic_stream_descriptor.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
  11. #define ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #include "asio/posix/basic_descriptor.hpp"
  17. #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \
  18. || defined(GENERATING_DOCUMENTATION)
  19. #include "asio/detail/push_options.hpp"
  20. namespace asio {
  21. namespace posix {
  22. /// Provides stream-oriented descriptor functionality.
  23. /**
  24. * The posix::basic_stream_descriptor class template provides asynchronous and
  25. * blocking stream-oriented descriptor functionality.
  26. *
  27. * @par Thread Safety
  28. * @e Distinct @e objects: Safe.@n
  29. * @e Shared @e objects: Unsafe.
  30. *
  31. * Synchronous @c read_some and @c write_some operations are thread safe with
  32. * respect to each other, if the underlying operating system calls are also
  33. * thread safe. This means that it is permitted to perform concurrent calls to
  34. * these synchronous operations on a single descriptor object. Other synchronous
  35. * operations, such as @c close, are not thread safe.
  36. *
  37. * @par Concepts:
  38. * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream.
  39. */
  40. template <typename Executor = any_io_executor>
  41. class basic_stream_descriptor
  42. : public basic_descriptor<Executor>
  43. {
  44. public:
  45. /// The type of the executor associated with the object.
  46. typedef Executor executor_type;
  47. /// Rebinds the descriptor type to another executor.
  48. template <typename Executor1>
  49. struct rebind_executor
  50. {
  51. /// The descriptor type when rebound to the specified executor.
  52. typedef basic_stream_descriptor<Executor1> other;
  53. };
  54. /// The native representation of a descriptor.
  55. typedef typename basic_descriptor<Executor>::native_handle_type
  56. native_handle_type;
  57. /// Construct a stream descriptor without opening it.
  58. /**
  59. * This constructor creates a stream descriptor without opening it. The
  60. * descriptor needs to be opened and then connected or accepted before data
  61. * can be sent or received on it.
  62. *
  63. * @param ex The I/O executor that the descriptor will use, by default, to
  64. * dispatch handlers for any asynchronous operations performed on the
  65. * descriptor.
  66. */
  67. explicit basic_stream_descriptor(const executor_type& ex)
  68. : basic_descriptor<Executor>(ex)
  69. {
  70. }
  71. /// Construct a stream descriptor without opening it.
  72. /**
  73. * This constructor creates a stream descriptor without opening it. The
  74. * descriptor needs to be opened and then connected or accepted before data
  75. * can be sent or received on it.
  76. *
  77. * @param context An execution context which provides the I/O executor that
  78. * the descriptor will use, by default, to dispatch handlers for any
  79. * asynchronous operations performed on the descriptor.
  80. */
  81. template <typename ExecutionContext>
  82. explicit basic_stream_descriptor(ExecutionContext& context,
  83. typename constraint<
  84. is_convertible<ExecutionContext&, execution_context&>::value,
  85. defaulted_constraint
  86. >::type = defaulted_constraint())
  87. : basic_descriptor<Executor>(context)
  88. {
  89. }
  90. /// Construct a stream descriptor on an existing native descriptor.
  91. /**
  92. * This constructor creates a stream descriptor object to hold an existing
  93. * native descriptor.
  94. *
  95. * @param ex The I/O executor that the descriptor will use, by default, to
  96. * dispatch handlers for any asynchronous operations performed on the
  97. * descriptor.
  98. *
  99. * @param native_descriptor The new underlying descriptor implementation.
  100. *
  101. * @throws asio::system_error Thrown on failure.
  102. */
  103. basic_stream_descriptor(const executor_type& ex,
  104. const native_handle_type& native_descriptor)
  105. : basic_descriptor<Executor>(ex, native_descriptor)
  106. {
  107. }
  108. /// Construct a stream descriptor on an existing native descriptor.
  109. /**
  110. * This constructor creates a stream descriptor object to hold an existing
  111. * native descriptor.
  112. *
  113. * @param context An execution context which provides the I/O executor that
  114. * the descriptor will use, by default, to dispatch handlers for any
  115. * asynchronous operations performed on the descriptor.
  116. *
  117. * @param native_descriptor The new underlying descriptor implementation.
  118. *
  119. * @throws asio::system_error Thrown on failure.
  120. */
  121. template <typename ExecutionContext>
  122. basic_stream_descriptor(ExecutionContext& context,
  123. const native_handle_type& native_descriptor,
  124. typename constraint<
  125. is_convertible<ExecutionContext&, execution_context&>::value
  126. >::type = 0)
  127. : basic_descriptor<Executor>(context, native_descriptor)
  128. {
  129. }
  130. #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  131. /// Move-construct a stream descriptor from another.
  132. /**
  133. * This constructor moves a stream descriptor from one object to another.
  134. *
  135. * @param other The other stream descriptor object from which the move
  136. * will occur.
  137. *
  138. * @note Following the move, the moved-from object is in the same state as if
  139. * constructed using the @c basic_stream_descriptor(const executor_type&)
  140. * constructor.
  141. */
  142. basic_stream_descriptor(basic_stream_descriptor&& other) ASIO_NOEXCEPT
  143. : basic_descriptor<Executor>(std::move(other))
  144. {
  145. }
  146. /// Move-assign a stream descriptor from another.
  147. /**
  148. * This assignment operator moves a stream descriptor from one object to
  149. * another.
  150. *
  151. * @param other The other stream descriptor object from which the move
  152. * will occur.
  153. *
  154. * @note Following the move, the moved-from object is in the same state as if
  155. * constructed using the @c basic_stream_descriptor(const executor_type&)
  156. * constructor.
  157. */
  158. basic_stream_descriptor& operator=(basic_stream_descriptor&& other)
  159. {
  160. basic_descriptor<Executor>::operator=(std::move(other));
  161. return *this;
  162. }
  163. #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  164. /// Write some data to the descriptor.
  165. /**
  166. * This function is used to write data to the stream descriptor. The function
  167. * call will block until one or more bytes of the data has been written
  168. * successfully, or until an error occurs.
  169. *
  170. * @param buffers One or more data buffers to be written to the descriptor.
  171. *
  172. * @returns The number of bytes written.
  173. *
  174. * @throws asio::system_error Thrown on failure. An error code of
  175. * asio::error::eof indicates that the connection was closed by the
  176. * peer.
  177. *
  178. * @note The write_some operation may not transmit all of the data to the
  179. * peer. Consider using the @ref write function if you need to ensure that
  180. * all data is written before the blocking operation completes.
  181. *
  182. * @par Example
  183. * To write a single data buffer use the @ref buffer function as follows:
  184. * @code
  185. * descriptor.write_some(asio::buffer(data, size));
  186. * @endcode
  187. * See the @ref buffer documentation for information on writing multiple
  188. * buffers in one go, and how to use it with arrays, boost::array or
  189. * std::vector.
  190. */
  191. template <typename ConstBufferSequence>
  192. std::size_t write_some(const ConstBufferSequence& buffers)
  193. {
  194. asio::error_code ec;
  195. std::size_t s = this->impl_.get_service().write_some(
  196. this->impl_.get_implementation(), buffers, ec);
  197. asio::detail::throw_error(ec, "write_some");
  198. return s;
  199. }
  200. /// Write some data to the descriptor.
  201. /**
  202. * This function is used to write data to the stream descriptor. The function
  203. * call will block until one or more bytes of the data has been written
  204. * successfully, or until an error occurs.
  205. *
  206. * @param buffers One or more data buffers to be written to the descriptor.
  207. *
  208. * @param ec Set to indicate what error occurred, if any.
  209. *
  210. * @returns The number of bytes written. Returns 0 if an error occurred.
  211. *
  212. * @note The write_some operation may not transmit all of the data to the
  213. * peer. Consider using the @ref write function if you need to ensure that
  214. * all data is written before the blocking operation completes.
  215. */
  216. template <typename ConstBufferSequence>
  217. std::size_t write_some(const ConstBufferSequence& buffers,
  218. asio::error_code& ec)
  219. {
  220. return this->impl_.get_service().write_some(
  221. this->impl_.get_implementation(), buffers, ec);
  222. }
  223. /// Start an asynchronous write.
  224. /**
  225. * This function is used to asynchronously write data to the stream
  226. * descriptor. It is an initiating function for an @ref
  227. * asynchronous_operation, and always returns immediately.
  228. *
  229. * @param buffers One or more data buffers to be written to the descriptor.
  230. * Although the buffers object may be copied as necessary, ownership of the
  231. * underlying memory blocks is retained by the caller, which must guarantee
  232. * that they remain valid until the completion handler is called.
  233. *
  234. * @param token The @ref completion_token that will be used to produce a
  235. * completion handler, which will be called when the write completes.
  236. * Potential completion tokens include @ref use_future, @ref use_awaitable,
  237. * @ref yield_context, or a function object with the correct completion
  238. * signature. The function signature of the completion handler must be:
  239. * @code void handler(
  240. * const asio::error_code& error, // Result of operation.
  241. * std::size_t bytes_transferred // Number of bytes written.
  242. * ); @endcode
  243. * Regardless of whether the asynchronous operation completes immediately or
  244. * not, the completion handler will not be invoked from within this function.
  245. * On immediate completion, invocation of the handler will be performed in a
  246. * manner equivalent to using asio::post().
  247. *
  248. * @par Completion Signature
  249. * @code void(asio::error_code, std::size_t) @endcode
  250. *
  251. * @note The write operation may not transmit all of the data to the peer.
  252. * Consider using the @ref async_write function if you need to ensure that all
  253. * data is written before the asynchronous operation completes.
  254. *
  255. * @par Example
  256. * To write a single data buffer use the @ref buffer function as follows:
  257. * @code
  258. * descriptor.async_write_some(asio::buffer(data, size), handler);
  259. * @endcode
  260. * See the @ref buffer documentation for information on writing multiple
  261. * buffers in one go, and how to use it with arrays, boost::array or
  262. * std::vector.
  263. *
  264. * @par Per-Operation Cancellation
  265. * This asynchronous operation supports cancellation for the following
  266. * asio::cancellation_type values:
  267. *
  268. * @li @c cancellation_type::terminal
  269. *
  270. * @li @c cancellation_type::partial
  271. *
  272. * @li @c cancellation_type::total
  273. */
  274. template <typename ConstBufferSequence,
  275. ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
  276. std::size_t)) WriteToken
  277. ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
  278. ASIO_INITFN_AUTO_RESULT_TYPE(WriteToken,
  279. void (asio::error_code, std::size_t))
  280. async_write_some(const ConstBufferSequence& buffers,
  281. ASIO_MOVE_ARG(WriteToken) token
  282. ASIO_DEFAULT_COMPLETION_TOKEN(executor_type))
  283. {
  284. return async_initiate<WriteToken,
  285. void (asio::error_code, std::size_t)>(
  286. initiate_async_write_some(this), token, buffers);
  287. }
  288. /// Read some data from the descriptor.
  289. /**
  290. * This function is used to read data from the stream descriptor. The function
  291. * call will block until one or more bytes of data has been read successfully,
  292. * or until an error occurs.
  293. *
  294. * @param buffers One or more buffers into which the data will be read.
  295. *
  296. * @returns The number of bytes read.
  297. *
  298. * @throws asio::system_error Thrown on failure. An error code of
  299. * asio::error::eof indicates that the connection was closed by the
  300. * peer.
  301. *
  302. * @note The read_some operation may not read all of the requested number of
  303. * bytes. Consider using the @ref read function if you need to ensure that
  304. * the requested amount of data is read before the blocking operation
  305. * completes.
  306. *
  307. * @par Example
  308. * To read into a single data buffer use the @ref buffer function as follows:
  309. * @code
  310. * descriptor.read_some(asio::buffer(data, size));
  311. * @endcode
  312. * See the @ref buffer documentation for information on reading into multiple
  313. * buffers in one go, and how to use it with arrays, boost::array or
  314. * std::vector.
  315. */
  316. template <typename MutableBufferSequence>
  317. std::size_t read_some(const MutableBufferSequence& buffers)
  318. {
  319. asio::error_code ec;
  320. std::size_t s = this->impl_.get_service().read_some(
  321. this->impl_.get_implementation(), buffers, ec);
  322. asio::detail::throw_error(ec, "read_some");
  323. return s;
  324. }
  325. /// Read some data from the descriptor.
  326. /**
  327. * This function is used to read data from the stream descriptor. The function
  328. * call will block until one or more bytes of data has been read successfully,
  329. * or until an error occurs.
  330. *
  331. * @param buffers One or more buffers into which the data will be read.
  332. *
  333. * @param ec Set to indicate what error occurred, if any.
  334. *
  335. * @returns The number of bytes read. Returns 0 if an error occurred.
  336. *
  337. * @note The read_some operation may not read all of the requested number of
  338. * bytes. Consider using the @ref read function if you need to ensure that
  339. * the requested amount of data is read before the blocking operation
  340. * completes.
  341. */
  342. template <typename MutableBufferSequence>
  343. std::size_t read_some(const MutableBufferSequence& buffers,
  344. asio::error_code& ec)
  345. {
  346. return this->impl_.get_service().read_some(
  347. this->impl_.get_implementation(), buffers, ec);
  348. }
  349. /// Start an asynchronous read.
  350. /**
  351. * This function is used to asynchronously read data from the stream
  352. * descriptor. It is an initiating function for an @ref
  353. * asynchronous_operation, and always returns immediately.
  354. *
  355. * @param buffers One or more buffers into which the data will be read.
  356. * Although the buffers object may be copied as necessary, ownership of the
  357. * underlying memory blocks is retained by the caller, which must guarantee
  358. * that they remain valid until the completion handler is called.
  359. *
  360. * @param token The @ref completion_token that will be used to produce a
  361. * completion handler, which will be called when the read completes.
  362. * Potential completion tokens include @ref use_future, @ref use_awaitable,
  363. * @ref yield_context, or a function object with the correct completion
  364. * signature. The function signature of the completion handler must be:
  365. * @code void handler(
  366. * const asio::error_code& error, // Result of operation.
  367. * std::size_t bytes_transferred // Number of bytes read.
  368. * ); @endcode
  369. * Regardless of whether the asynchronous operation completes immediately or
  370. * not, the completion handler will not be invoked from within this function.
  371. * On immediate completion, invocation of the handler will be performed in a
  372. * manner equivalent to using asio::post().
  373. *
  374. * @par Completion Signature
  375. * @code void(asio::error_code, std::size_t) @endcode
  376. *
  377. * @note The read operation may not read all of the requested number of bytes.
  378. * Consider using the @ref async_read function if you need to ensure that the
  379. * requested amount of data is read before the asynchronous operation
  380. * completes.
  381. *
  382. * @par Example
  383. * To read into a single data buffer use the @ref buffer function as follows:
  384. * @code
  385. * descriptor.async_read_some(asio::buffer(data, size), handler);
  386. * @endcode
  387. * See the @ref buffer documentation for information on reading into multiple
  388. * buffers in one go, and how to use it with arrays, boost::array or
  389. * std::vector.
  390. *
  391. * @par Per-Operation Cancellation
  392. * This asynchronous operation supports cancellation for the following
  393. * asio::cancellation_type values:
  394. *
  395. * @li @c cancellation_type::terminal
  396. *
  397. * @li @c cancellation_type::partial
  398. *
  399. * @li @c cancellation_type::total
  400. */
  401. template <typename MutableBufferSequence,
  402. ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
  403. std::size_t)) ReadToken
  404. ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
  405. ASIO_INITFN_AUTO_RESULT_TYPE(ReadToken,
  406. void (asio::error_code, std::size_t))
  407. async_read_some(const MutableBufferSequence& buffers,
  408. ASIO_MOVE_ARG(ReadToken) token
  409. ASIO_DEFAULT_COMPLETION_TOKEN(executor_type))
  410. {
  411. return async_initiate<ReadToken,
  412. void (asio::error_code, std::size_t)>(
  413. initiate_async_read_some(this), token, buffers);
  414. }
  415. private:
  416. class initiate_async_write_some
  417. {
  418. public:
  419. typedef Executor executor_type;
  420. explicit initiate_async_write_some(basic_stream_descriptor* self)
  421. : self_(self)
  422. {
  423. }
  424. executor_type get_executor() const ASIO_NOEXCEPT
  425. {
  426. return self_->get_executor();
  427. }
  428. template <typename WriteHandler, typename ConstBufferSequence>
  429. void operator()(ASIO_MOVE_ARG(WriteHandler) handler,
  430. const ConstBufferSequence& buffers) const
  431. {
  432. // If you get an error on the following line it means that your handler
  433. // does not meet the documented type requirements for a WriteHandler.
  434. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
  435. detail::non_const_lvalue<WriteHandler> handler2(handler);
  436. self_->impl_.get_service().async_write_some(
  437. self_->impl_.get_implementation(), buffers,
  438. handler2.value, self_->impl_.get_executor());
  439. }
  440. private:
  441. basic_stream_descriptor* self_;
  442. };
  443. class initiate_async_read_some
  444. {
  445. public:
  446. typedef Executor executor_type;
  447. explicit initiate_async_read_some(basic_stream_descriptor* self)
  448. : self_(self)
  449. {
  450. }
  451. executor_type get_executor() const ASIO_NOEXCEPT
  452. {
  453. return self_->get_executor();
  454. }
  455. template <typename ReadHandler, typename MutableBufferSequence>
  456. void operator()(ASIO_MOVE_ARG(ReadHandler) handler,
  457. const MutableBufferSequence& buffers) const
  458. {
  459. // If you get an error on the following line it means that your handler
  460. // does not meet the documented type requirements for a ReadHandler.
  461. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
  462. detail::non_const_lvalue<ReadHandler> handler2(handler);
  463. self_->impl_.get_service().async_read_some(
  464. self_->impl_.get_implementation(), buffers,
  465. handler2.value, self_->impl_.get_executor());
  466. }
  467. private:
  468. basic_stream_descriptor* self_;
  469. };
  470. };
  471. } // namespace posix
  472. } // namespace asio
  473. #include "asio/detail/pop_options.hpp"
  474. #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
  475. // || defined(GENERATING_DOCUMENTATION)
  476. #endif // ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP