Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1857 lines
60KB

  1. //
  2. // basic_socket.hpp
  3. // ~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 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_BASIC_SOCKET_HPP
  11. #define ASIO_BASIC_SOCKET_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/async_result.hpp"
  17. #include "asio/detail/handler_type_requirements.hpp"
  18. #include "asio/detail/io_object_impl.hpp"
  19. #include "asio/detail/non_const_lvalue.hpp"
  20. #include "asio/detail/throw_error.hpp"
  21. #include "asio/detail/type_traits.hpp"
  22. #include "asio/error.hpp"
  23. #include "asio/execution_context.hpp"
  24. #include "asio/executor.hpp"
  25. #include "asio/post.hpp"
  26. #include "asio/socket_base.hpp"
  27. #if defined(ASIO_WINDOWS_RUNTIME)
  28. # include "asio/detail/null_socket_service.hpp"
  29. #elif defined(ASIO_HAS_IOCP)
  30. # include "asio/detail/win_iocp_socket_service.hpp"
  31. #else
  32. # include "asio/detail/reactive_socket_service.hpp"
  33. #endif
  34. #if defined(ASIO_HAS_MOVE)
  35. # include <utility>
  36. #endif // defined(ASIO_HAS_MOVE)
  37. #include "asio/detail/push_options.hpp"
  38. namespace asio {
  39. #if !defined(ASIO_BASIC_SOCKET_FWD_DECL)
  40. #define ASIO_BASIC_SOCKET_FWD_DECL
  41. // Forward declaration with defaulted arguments.
  42. template <typename Protocol, typename Executor = executor>
  43. class basic_socket;
  44. #endif // !defined(ASIO_BASIC_SOCKET_FWD_DECL)
  45. /// Provides socket functionality.
  46. /**
  47. * The basic_socket class template provides functionality that is common to both
  48. * stream-oriented and datagram-oriented sockets.
  49. *
  50. * @par Thread Safety
  51. * @e Distinct @e objects: Safe.@n
  52. * @e Shared @e objects: Unsafe.
  53. */
  54. template <typename Protocol, typename Executor>
  55. class basic_socket
  56. : public socket_base
  57. {
  58. public:
  59. /// The type of the executor associated with the object.
  60. typedef Executor executor_type;
  61. /// Rebinds the socket type to another executor.
  62. template <typename Executor1>
  63. struct rebind_executor
  64. {
  65. /// The socket type when rebound to the specified executor.
  66. typedef basic_socket<Protocol, Executor1> other;
  67. };
  68. /// The native representation of a socket.
  69. #if defined(GENERATING_DOCUMENTATION)
  70. typedef implementation_defined native_handle_type;
  71. #elif defined(ASIO_WINDOWS_RUNTIME)
  72. typedef typename detail::null_socket_service<
  73. Protocol>::native_handle_type native_handle_type;
  74. #elif defined(ASIO_HAS_IOCP)
  75. typedef typename detail::win_iocp_socket_service<
  76. Protocol>::native_handle_type native_handle_type;
  77. #else
  78. typedef typename detail::reactive_socket_service<
  79. Protocol>::native_handle_type native_handle_type;
  80. #endif
  81. /// The protocol type.
  82. typedef Protocol protocol_type;
  83. /// The endpoint type.
  84. typedef typename Protocol::endpoint endpoint_type;
  85. #if !defined(ASIO_NO_EXTENSIONS)
  86. /// A basic_socket is always the lowest layer.
  87. typedef basic_socket<Protocol, Executor> lowest_layer_type;
  88. #endif // !defined(ASIO_NO_EXTENSIONS)
  89. /// Construct a basic_socket without opening it.
  90. /**
  91. * This constructor creates a socket without opening it.
  92. *
  93. * @param ex The I/O executor that the socket will use, by default, to
  94. * dispatch handlers for any asynchronous operations performed on the socket.
  95. */
  96. explicit basic_socket(const executor_type& ex)
  97. : impl_(ex)
  98. {
  99. }
  100. /// Construct a basic_socket without opening it.
  101. /**
  102. * This constructor creates a socket without opening it.
  103. *
  104. * @param context An execution context which provides the I/O executor that
  105. * the socket will use, by default, to dispatch handlers for any asynchronous
  106. * operations performed on the socket.
  107. */
  108. template <typename ExecutionContext>
  109. explicit basic_socket(ExecutionContext& context,
  110. typename enable_if<
  111. is_convertible<ExecutionContext&, execution_context&>::value
  112. >::type* = 0)
  113. : impl_(context)
  114. {
  115. }
  116. /// Construct and open a basic_socket.
  117. /**
  118. * This constructor creates and opens a socket.
  119. *
  120. * @param ex The I/O executor that the socket will use, by default, to
  121. * dispatch handlers for any asynchronous operations performed on the socket.
  122. *
  123. * @param protocol An object specifying protocol parameters to be used.
  124. *
  125. * @throws asio::system_error Thrown on failure.
  126. */
  127. basic_socket(const executor_type& ex, const protocol_type& protocol)
  128. : impl_(ex)
  129. {
  130. asio::error_code ec;
  131. impl_.get_service().open(impl_.get_implementation(), protocol, ec);
  132. asio::detail::throw_error(ec, "open");
  133. }
  134. /// Construct and open a basic_socket.
  135. /**
  136. * This constructor creates and opens a socket.
  137. *
  138. * @param context An execution context which provides the I/O executor that
  139. * the socket will use, by default, to dispatch handlers for any asynchronous
  140. * operations performed on the socket.
  141. *
  142. * @param protocol An object specifying protocol parameters to be used.
  143. *
  144. * @throws asio::system_error Thrown on failure.
  145. */
  146. template <typename ExecutionContext>
  147. basic_socket(ExecutionContext& context, const protocol_type& protocol,
  148. typename enable_if<
  149. is_convertible<ExecutionContext&, execution_context&>::value
  150. >::type* = 0)
  151. : impl_(context)
  152. {
  153. asio::error_code ec;
  154. impl_.get_service().open(impl_.get_implementation(), protocol, ec);
  155. asio::detail::throw_error(ec, "open");
  156. }
  157. /// Construct a basic_socket, opening it and binding it to the given local
  158. /// endpoint.
  159. /**
  160. * This constructor creates a socket and automatically opens it bound to the
  161. * specified endpoint on the local machine. The protocol used is the protocol
  162. * associated with the given endpoint.
  163. *
  164. * @param ex The I/O executor that the socket will use, by default, to
  165. * dispatch handlers for any asynchronous operations performed on the socket.
  166. *
  167. * @param endpoint An endpoint on the local machine to which the socket will
  168. * be bound.
  169. *
  170. * @throws asio::system_error Thrown on failure.
  171. */
  172. basic_socket(const executor_type& ex, const endpoint_type& endpoint)
  173. : impl_(ex)
  174. {
  175. asio::error_code ec;
  176. const protocol_type protocol = endpoint.protocol();
  177. impl_.get_service().open(impl_.get_implementation(), protocol, ec);
  178. asio::detail::throw_error(ec, "open");
  179. impl_.get_service().bind(impl_.get_implementation(), endpoint, ec);
  180. asio::detail::throw_error(ec, "bind");
  181. }
  182. /// Construct a basic_socket, opening it and binding it to the given local
  183. /// endpoint.
  184. /**
  185. * This constructor creates a socket and automatically opens it bound to the
  186. * specified endpoint on the local machine. The protocol used is the protocol
  187. * associated with the given endpoint.
  188. *
  189. * @param context An execution context which provides the I/O executor that
  190. * the socket will use, by default, to dispatch handlers for any asynchronous
  191. * operations performed on the socket.
  192. *
  193. * @param endpoint An endpoint on the local machine to which the socket will
  194. * be bound.
  195. *
  196. * @throws asio::system_error Thrown on failure.
  197. */
  198. template <typename ExecutionContext>
  199. basic_socket(ExecutionContext& context, const endpoint_type& endpoint,
  200. typename enable_if<
  201. is_convertible<ExecutionContext&, execution_context&>::value
  202. >::type* = 0)
  203. : impl_(context)
  204. {
  205. asio::error_code ec;
  206. const protocol_type protocol = endpoint.protocol();
  207. impl_.get_service().open(impl_.get_implementation(), protocol, ec);
  208. asio::detail::throw_error(ec, "open");
  209. impl_.get_service().bind(impl_.get_implementation(), endpoint, ec);
  210. asio::detail::throw_error(ec, "bind");
  211. }
  212. /// Construct a basic_socket on an existing native socket.
  213. /**
  214. * This constructor creates a socket object to hold an existing native socket.
  215. *
  216. * @param ex The I/O executor that the socket will use, by default, to
  217. * dispatch handlers for any asynchronous operations performed on the socket.
  218. *
  219. * @param protocol An object specifying protocol parameters to be used.
  220. *
  221. * @param native_socket A native socket.
  222. *
  223. * @throws asio::system_error Thrown on failure.
  224. */
  225. basic_socket(const executor_type& ex, const protocol_type& protocol,
  226. const native_handle_type& native_socket)
  227. : impl_(ex)
  228. {
  229. asio::error_code ec;
  230. impl_.get_service().assign(impl_.get_implementation(),
  231. protocol, native_socket, ec);
  232. asio::detail::throw_error(ec, "assign");
  233. }
  234. /// Construct a basic_socket on an existing native socket.
  235. /**
  236. * This constructor creates a socket object to hold an existing native socket.
  237. *
  238. * @param context An execution context which provides the I/O executor that
  239. * the socket will use, by default, to dispatch handlers for any asynchronous
  240. * operations performed on the socket.
  241. *
  242. * @param protocol An object specifying protocol parameters to be used.
  243. *
  244. * @param native_socket A native socket.
  245. *
  246. * @throws asio::system_error Thrown on failure.
  247. */
  248. template <typename ExecutionContext>
  249. basic_socket(ExecutionContext& context, const protocol_type& protocol,
  250. const native_handle_type& native_socket,
  251. typename enable_if<
  252. is_convertible<ExecutionContext&, execution_context&>::value
  253. >::type* = 0)
  254. : impl_(context)
  255. {
  256. asio::error_code ec;
  257. impl_.get_service().assign(impl_.get_implementation(),
  258. protocol, native_socket, ec);
  259. asio::detail::throw_error(ec, "assign");
  260. }
  261. #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  262. /// Move-construct a basic_socket from another.
  263. /**
  264. * This constructor moves a socket from one object to another.
  265. *
  266. * @param other The other basic_socket object from which the move will
  267. * occur.
  268. *
  269. * @note Following the move, the moved-from object is in the same state as if
  270. * constructed using the @c basic_socket(const executor_type&) constructor.
  271. */
  272. basic_socket(basic_socket&& other)
  273. : impl_(std::move(other.impl_))
  274. {
  275. }
  276. /// Move-assign a basic_socket from another.
  277. /**
  278. * This assignment operator moves a socket from one object to another.
  279. *
  280. * @param other The other basic_socket object from which the move will
  281. * occur.
  282. *
  283. * @note Following the move, the moved-from object is in the same state as if
  284. * constructed using the @c basic_socket(const executor_type&) constructor.
  285. */
  286. basic_socket& operator=(basic_socket&& other)
  287. {
  288. impl_ = std::move(other.impl_);
  289. return *this;
  290. }
  291. // All sockets have access to each other's implementations.
  292. template <typename Protocol1, typename Executor1>
  293. friend class basic_socket;
  294. /// Move-construct a basic_socket from a socket of another protocol type.
  295. /**
  296. * This constructor moves a socket from one object to another.
  297. *
  298. * @param other The other basic_socket object from which the move will
  299. * occur.
  300. *
  301. * @note Following the move, the moved-from object is in the same state as if
  302. * constructed using the @c basic_socket(const executor_type&) constructor.
  303. */
  304. template <typename Protocol1, typename Executor1>
  305. basic_socket(basic_socket<Protocol1, Executor1>&& other,
  306. typename enable_if<
  307. is_convertible<Protocol1, Protocol>::value
  308. && is_convertible<Executor1, Executor>::value
  309. >::type* = 0)
  310. : impl_(std::move(other.impl_))
  311. {
  312. }
  313. /// Move-assign a basic_socket from a socket of another protocol type.
  314. /**
  315. * This assignment operator moves a socket from one object to another.
  316. *
  317. * @param other The other basic_socket object from which the move will
  318. * occur.
  319. *
  320. * @note Following the move, the moved-from object is in the same state as if
  321. * constructed using the @c basic_socket(const executor_type&) constructor.
  322. */
  323. template <typename Protocol1, typename Executor1>
  324. typename enable_if<
  325. is_convertible<Protocol1, Protocol>::value
  326. && is_convertible<Executor1, Executor>::value,
  327. basic_socket&
  328. >::type operator=(basic_socket<Protocol1, Executor1> && other)
  329. {
  330. basic_socket tmp(std::move(other));
  331. impl_ = std::move(tmp.impl_);
  332. return *this;
  333. }
  334. #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  335. /// Get the executor associated with the object.
  336. executor_type get_executor() ASIO_NOEXCEPT
  337. {
  338. return impl_.get_executor();
  339. }
  340. #if !defined(ASIO_NO_EXTENSIONS)
  341. /// Get a reference to the lowest layer.
  342. /**
  343. * This function returns a reference to the lowest layer in a stack of
  344. * layers. Since a basic_socket cannot contain any further layers, it simply
  345. * returns a reference to itself.
  346. *
  347. * @return A reference to the lowest layer in the stack of layers. Ownership
  348. * is not transferred to the caller.
  349. */
  350. lowest_layer_type& lowest_layer()
  351. {
  352. return *this;
  353. }
  354. /// Get a const reference to the lowest layer.
  355. /**
  356. * This function returns a const reference to the lowest layer in a stack of
  357. * layers. Since a basic_socket cannot contain any further layers, it simply
  358. * returns a reference to itself.
  359. *
  360. * @return A const reference to the lowest layer in the stack of layers.
  361. * Ownership is not transferred to the caller.
  362. */
  363. const lowest_layer_type& lowest_layer() const
  364. {
  365. return *this;
  366. }
  367. #endif // !defined(ASIO_NO_EXTENSIONS)
  368. /// Open the socket using the specified protocol.
  369. /**
  370. * This function opens the socket so that it will use the specified protocol.
  371. *
  372. * @param protocol An object specifying protocol parameters to be used.
  373. *
  374. * @throws asio::system_error Thrown on failure.
  375. *
  376. * @par Example
  377. * @code
  378. * asio::ip::tcp::socket socket(my_context);
  379. * socket.open(asio::ip::tcp::v4());
  380. * @endcode
  381. */
  382. void open(const protocol_type& protocol = protocol_type())
  383. {
  384. asio::error_code ec;
  385. impl_.get_service().open(impl_.get_implementation(), protocol, ec);
  386. asio::detail::throw_error(ec, "open");
  387. }
  388. /// Open the socket using the specified protocol.
  389. /**
  390. * This function opens the socket so that it will use the specified protocol.
  391. *
  392. * @param protocol An object specifying which protocol is to be used.
  393. *
  394. * @param ec Set to indicate what error occurred, if any.
  395. *
  396. * @par Example
  397. * @code
  398. * asio::ip::tcp::socket socket(my_context);
  399. * asio::error_code ec;
  400. * socket.open(asio::ip::tcp::v4(), ec);
  401. * if (ec)
  402. * {
  403. * // An error occurred.
  404. * }
  405. * @endcode
  406. */
  407. ASIO_SYNC_OP_VOID open(const protocol_type& protocol,
  408. asio::error_code& ec)
  409. {
  410. impl_.get_service().open(impl_.get_implementation(), protocol, ec);
  411. ASIO_SYNC_OP_VOID_RETURN(ec);
  412. }
  413. /// Assign an existing native socket to the socket.
  414. /*
  415. * This function opens the socket to hold an existing native socket.
  416. *
  417. * @param protocol An object specifying which protocol is to be used.
  418. *
  419. * @param native_socket A native socket.
  420. *
  421. * @throws asio::system_error Thrown on failure.
  422. */
  423. void assign(const protocol_type& protocol,
  424. const native_handle_type& native_socket)
  425. {
  426. asio::error_code ec;
  427. impl_.get_service().assign(impl_.get_implementation(),
  428. protocol, native_socket, ec);
  429. asio::detail::throw_error(ec, "assign");
  430. }
  431. /// Assign an existing native socket to the socket.
  432. /*
  433. * This function opens the socket to hold an existing native socket.
  434. *
  435. * @param protocol An object specifying which protocol is to be used.
  436. *
  437. * @param native_socket A native socket.
  438. *
  439. * @param ec Set to indicate what error occurred, if any.
  440. */
  441. ASIO_SYNC_OP_VOID assign(const protocol_type& protocol,
  442. const native_handle_type& native_socket, asio::error_code& ec)
  443. {
  444. impl_.get_service().assign(impl_.get_implementation(),
  445. protocol, native_socket, ec);
  446. ASIO_SYNC_OP_VOID_RETURN(ec);
  447. }
  448. /// Determine whether the socket is open.
  449. bool is_open() const
  450. {
  451. return impl_.get_service().is_open(impl_.get_implementation());
  452. }
  453. /// Close the socket.
  454. /**
  455. * This function is used to close the socket. Any asynchronous send, receive
  456. * or connect operations will be cancelled immediately, and will complete
  457. * with the asio::error::operation_aborted error.
  458. *
  459. * @throws asio::system_error Thrown on failure. Note that, even if
  460. * the function indicates an error, the underlying descriptor is closed.
  461. *
  462. * @note For portable behaviour with respect to graceful closure of a
  463. * connected socket, call shutdown() before closing the socket.
  464. */
  465. void close()
  466. {
  467. asio::error_code ec;
  468. impl_.get_service().close(impl_.get_implementation(), ec);
  469. asio::detail::throw_error(ec, "close");
  470. }
  471. /// Close the socket.
  472. /**
  473. * This function is used to close the socket. Any asynchronous send, receive
  474. * or connect operations will be cancelled immediately, and will complete
  475. * with the asio::error::operation_aborted error.
  476. *
  477. * @param ec Set to indicate what error occurred, if any. Note that, even if
  478. * the function indicates an error, the underlying descriptor is closed.
  479. *
  480. * @par Example
  481. * @code
  482. * asio::ip::tcp::socket socket(my_context);
  483. * ...
  484. * asio::error_code ec;
  485. * socket.close(ec);
  486. * if (ec)
  487. * {
  488. * // An error occurred.
  489. * }
  490. * @endcode
  491. *
  492. * @note For portable behaviour with respect to graceful closure of a
  493. * connected socket, call shutdown() before closing the socket.
  494. */
  495. ASIO_SYNC_OP_VOID close(asio::error_code& ec)
  496. {
  497. impl_.get_service().close(impl_.get_implementation(), ec);
  498. ASIO_SYNC_OP_VOID_RETURN(ec);
  499. }
  500. /// Release ownership of the underlying native socket.
  501. /**
  502. * This function causes all outstanding asynchronous connect, send and receive
  503. * operations to finish immediately, and the handlers for cancelled operations
  504. * will be passed the asio::error::operation_aborted error. Ownership
  505. * of the native socket is then transferred to the caller.
  506. *
  507. * @throws asio::system_error Thrown on failure.
  508. *
  509. * @note This function is unsupported on Windows versions prior to Windows
  510. * 8.1, and will fail with asio::error::operation_not_supported on
  511. * these platforms.
  512. */
  513. #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \
  514. && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603)
  515. __declspec(deprecated("This function always fails with "
  516. "operation_not_supported when used on Windows versions "
  517. "prior to Windows 8.1."))
  518. #endif
  519. native_handle_type release()
  520. {
  521. asio::error_code ec;
  522. native_handle_type s = impl_.get_service().release(
  523. impl_.get_implementation(), ec);
  524. asio::detail::throw_error(ec, "release");
  525. return s;
  526. }
  527. /// Release ownership of the underlying native socket.
  528. /**
  529. * This function causes all outstanding asynchronous connect, send and receive
  530. * operations to finish immediately, and the handlers for cancelled operations
  531. * will be passed the asio::error::operation_aborted error. Ownership
  532. * of the native socket is then transferred to the caller.
  533. *
  534. * @param ec Set to indicate what error occurred, if any.
  535. *
  536. * @note This function is unsupported on Windows versions prior to Windows
  537. * 8.1, and will fail with asio::error::operation_not_supported on
  538. * these platforms.
  539. */
  540. #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \
  541. && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603)
  542. __declspec(deprecated("This function always fails with "
  543. "operation_not_supported when used on Windows versions "
  544. "prior to Windows 8.1."))
  545. #endif
  546. native_handle_type release(asio::error_code& ec)
  547. {
  548. return impl_.get_service().release(impl_.get_implementation(), ec);
  549. }
  550. /// Get the native socket representation.
  551. /**
  552. * This function may be used to obtain the underlying representation of the
  553. * socket. This is intended to allow access to native socket functionality
  554. * that is not otherwise provided.
  555. */
  556. native_handle_type native_handle()
  557. {
  558. return impl_.get_service().native_handle(impl_.get_implementation());
  559. }
  560. /// Cancel all asynchronous operations associated with the socket.
  561. /**
  562. * This function causes all outstanding asynchronous connect, send and receive
  563. * operations to finish immediately, and the handlers for cancelled operations
  564. * will be passed the asio::error::operation_aborted error.
  565. *
  566. * @throws asio::system_error Thrown on failure.
  567. *
  568. * @note Calls to cancel() will always fail with
  569. * asio::error::operation_not_supported when run on Windows XP, Windows
  570. * Server 2003, and earlier versions of Windows, unless
  571. * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has
  572. * two issues that should be considered before enabling its use:
  573. *
  574. * @li It will only cancel asynchronous operations that were initiated in the
  575. * current thread.
  576. *
  577. * @li It can appear to complete without error, but the request to cancel the
  578. * unfinished operations may be silently ignored by the operating system.
  579. * Whether it works or not seems to depend on the drivers that are installed.
  580. *
  581. * For portable cancellation, consider using one of the following
  582. * alternatives:
  583. *
  584. * @li Disable asio's I/O completion port backend by defining
  585. * ASIO_DISABLE_IOCP.
  586. *
  587. * @li Use the close() function to simultaneously cancel the outstanding
  588. * operations and close the socket.
  589. *
  590. * When running on Windows Vista, Windows Server 2008, and later, the
  591. * CancelIoEx function is always used. This function does not have the
  592. * problems described above.
  593. */
  594. #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \
  595. && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \
  596. && !defined(ASIO_ENABLE_CANCELIO)
  597. __declspec(deprecated("By default, this function always fails with "
  598. "operation_not_supported when used on Windows XP, Windows Server 2003, "
  599. "or earlier. Consult documentation for details."))
  600. #endif
  601. void cancel()
  602. {
  603. asio::error_code ec;
  604. impl_.get_service().cancel(impl_.get_implementation(), ec);
  605. asio::detail::throw_error(ec, "cancel");
  606. }
  607. /// Cancel all asynchronous operations associated with the socket.
  608. /**
  609. * This function causes all outstanding asynchronous connect, send and receive
  610. * operations to finish immediately, and the handlers for cancelled operations
  611. * will be passed the asio::error::operation_aborted error.
  612. *
  613. * @param ec Set to indicate what error occurred, if any.
  614. *
  615. * @note Calls to cancel() will always fail with
  616. * asio::error::operation_not_supported when run on Windows XP, Windows
  617. * Server 2003, and earlier versions of Windows, unless
  618. * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has
  619. * two issues that should be considered before enabling its use:
  620. *
  621. * @li It will only cancel asynchronous operations that were initiated in the
  622. * current thread.
  623. *
  624. * @li It can appear to complete without error, but the request to cancel the
  625. * unfinished operations may be silently ignored by the operating system.
  626. * Whether it works or not seems to depend on the drivers that are installed.
  627. *
  628. * For portable cancellation, consider using one of the following
  629. * alternatives:
  630. *
  631. * @li Disable asio's I/O completion port backend by defining
  632. * ASIO_DISABLE_IOCP.
  633. *
  634. * @li Use the close() function to simultaneously cancel the outstanding
  635. * operations and close the socket.
  636. *
  637. * When running on Windows Vista, Windows Server 2008, and later, the
  638. * CancelIoEx function is always used. This function does not have the
  639. * problems described above.
  640. */
  641. #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \
  642. && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \
  643. && !defined(ASIO_ENABLE_CANCELIO)
  644. __declspec(deprecated("By default, this function always fails with "
  645. "operation_not_supported when used on Windows XP, Windows Server 2003, "
  646. "or earlier. Consult documentation for details."))
  647. #endif
  648. ASIO_SYNC_OP_VOID cancel(asio::error_code& ec)
  649. {
  650. impl_.get_service().cancel(impl_.get_implementation(), ec);
  651. ASIO_SYNC_OP_VOID_RETURN(ec);
  652. }
  653. /// Determine whether the socket is at the out-of-band data mark.
  654. /**
  655. * This function is used to check whether the socket input is currently
  656. * positioned at the out-of-band data mark.
  657. *
  658. * @return A bool indicating whether the socket is at the out-of-band data
  659. * mark.
  660. *
  661. * @throws asio::system_error Thrown on failure.
  662. */
  663. bool at_mark() const
  664. {
  665. asio::error_code ec;
  666. bool b = impl_.get_service().at_mark(impl_.get_implementation(), ec);
  667. asio::detail::throw_error(ec, "at_mark");
  668. return b;
  669. }
  670. /// Determine whether the socket is at the out-of-band data mark.
  671. /**
  672. * This function is used to check whether the socket input is currently
  673. * positioned at the out-of-band data mark.
  674. *
  675. * @param ec Set to indicate what error occurred, if any.
  676. *
  677. * @return A bool indicating whether the socket is at the out-of-band data
  678. * mark.
  679. */
  680. bool at_mark(asio::error_code& ec) const
  681. {
  682. return impl_.get_service().at_mark(impl_.get_implementation(), ec);
  683. }
  684. /// Determine the number of bytes available for reading.
  685. /**
  686. * This function is used to determine the number of bytes that may be read
  687. * without blocking.
  688. *
  689. * @return The number of bytes that may be read without blocking, or 0 if an
  690. * error occurs.
  691. *
  692. * @throws asio::system_error Thrown on failure.
  693. */
  694. std::size_t available() const
  695. {
  696. asio::error_code ec;
  697. std::size_t s = impl_.get_service().available(
  698. impl_.get_implementation(), ec);
  699. asio::detail::throw_error(ec, "available");
  700. return s;
  701. }
  702. /// Determine the number of bytes available for reading.
  703. /**
  704. * This function is used to determine the number of bytes that may be read
  705. * without blocking.
  706. *
  707. * @param ec Set to indicate what error occurred, if any.
  708. *
  709. * @return The number of bytes that may be read without blocking, or 0 if an
  710. * error occurs.
  711. */
  712. std::size_t available(asio::error_code& ec) const
  713. {
  714. return impl_.get_service().available(impl_.get_implementation(), ec);
  715. }
  716. /// Bind the socket to the given local endpoint.
  717. /**
  718. * This function binds the socket to the specified endpoint on the local
  719. * machine.
  720. *
  721. * @param endpoint An endpoint on the local machine to which the socket will
  722. * be bound.
  723. *
  724. * @throws asio::system_error Thrown on failure.
  725. *
  726. * @par Example
  727. * @code
  728. * asio::ip::tcp::socket socket(my_context);
  729. * socket.open(asio::ip::tcp::v4());
  730. * socket.bind(asio::ip::tcp::endpoint(
  731. * asio::ip::tcp::v4(), 12345));
  732. * @endcode
  733. */
  734. void bind(const endpoint_type& endpoint)
  735. {
  736. asio::error_code ec;
  737. impl_.get_service().bind(impl_.get_implementation(), endpoint, ec);
  738. asio::detail::throw_error(ec, "bind");
  739. }
  740. /// Bind the socket to the given local endpoint.
  741. /**
  742. * This function binds the socket to the specified endpoint on the local
  743. * machine.
  744. *
  745. * @param endpoint An endpoint on the local machine to which the socket will
  746. * be bound.
  747. *
  748. * @param ec Set to indicate what error occurred, if any.
  749. *
  750. * @par Example
  751. * @code
  752. * asio::ip::tcp::socket socket(my_context);
  753. * socket.open(asio::ip::tcp::v4());
  754. * asio::error_code ec;
  755. * socket.bind(asio::ip::tcp::endpoint(
  756. * asio::ip::tcp::v4(), 12345), ec);
  757. * if (ec)
  758. * {
  759. * // An error occurred.
  760. * }
  761. * @endcode
  762. */
  763. ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint,
  764. asio::error_code& ec)
  765. {
  766. impl_.get_service().bind(impl_.get_implementation(), endpoint, ec);
  767. ASIO_SYNC_OP_VOID_RETURN(ec);
  768. }
  769. /// Connect the socket to the specified endpoint.
  770. /**
  771. * This function is used to connect a socket to the specified remote endpoint.
  772. * The function call will block until the connection is successfully made or
  773. * an error occurs.
  774. *
  775. * The socket is automatically opened if it is not already open. If the
  776. * connect fails, and the socket was automatically opened, the socket is
  777. * not returned to the closed state.
  778. *
  779. * @param peer_endpoint The remote endpoint to which the socket will be
  780. * connected.
  781. *
  782. * @throws asio::system_error Thrown on failure.
  783. *
  784. * @par Example
  785. * @code
  786. * asio::ip::tcp::socket socket(my_context);
  787. * asio::ip::tcp::endpoint endpoint(
  788. * asio::ip::address::from_string("1.2.3.4"), 12345);
  789. * socket.connect(endpoint);
  790. * @endcode
  791. */
  792. void connect(const endpoint_type& peer_endpoint)
  793. {
  794. asio::error_code ec;
  795. if (!is_open())
  796. {
  797. impl_.get_service().open(impl_.get_implementation(),
  798. peer_endpoint.protocol(), ec);
  799. asio::detail::throw_error(ec, "connect");
  800. }
  801. impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec);
  802. asio::detail::throw_error(ec, "connect");
  803. }
  804. /// Connect the socket to the specified endpoint.
  805. /**
  806. * This function is used to connect a socket to the specified remote endpoint.
  807. * The function call will block until the connection is successfully made or
  808. * an error occurs.
  809. *
  810. * The socket is automatically opened if it is not already open. If the
  811. * connect fails, and the socket was automatically opened, the socket is
  812. * not returned to the closed state.
  813. *
  814. * @param peer_endpoint The remote endpoint to which the socket will be
  815. * connected.
  816. *
  817. * @param ec Set to indicate what error occurred, if any.
  818. *
  819. * @par Example
  820. * @code
  821. * asio::ip::tcp::socket socket(my_context);
  822. * asio::ip::tcp::endpoint endpoint(
  823. * asio::ip::address::from_string("1.2.3.4"), 12345);
  824. * asio::error_code ec;
  825. * socket.connect(endpoint, ec);
  826. * if (ec)
  827. * {
  828. * // An error occurred.
  829. * }
  830. * @endcode
  831. */
  832. ASIO_SYNC_OP_VOID connect(const endpoint_type& peer_endpoint,
  833. asio::error_code& ec)
  834. {
  835. if (!is_open())
  836. {
  837. impl_.get_service().open(impl_.get_implementation(),
  838. peer_endpoint.protocol(), ec);
  839. if (ec)
  840. {
  841. ASIO_SYNC_OP_VOID_RETURN(ec);
  842. }
  843. }
  844. impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec);
  845. ASIO_SYNC_OP_VOID_RETURN(ec);
  846. }
  847. /// Start an asynchronous connect.
  848. /**
  849. * This function is used to asynchronously connect a socket to the specified
  850. * remote endpoint. The function call always returns immediately.
  851. *
  852. * The socket is automatically opened if it is not already open. If the
  853. * connect fails, and the socket was automatically opened, the socket is
  854. * not returned to the closed state.
  855. *
  856. * @param peer_endpoint The remote endpoint to which the socket will be
  857. * connected. Copies will be made of the endpoint object as required.
  858. *
  859. * @param handler The handler to be called when the connection operation
  860. * completes. Copies will be made of the handler as required. The function
  861. * signature of the handler must be:
  862. * @code void handler(
  863. * const asio::error_code& error // Result of operation
  864. * ); @endcode
  865. * Regardless of whether the asynchronous operation completes immediately or
  866. * not, the handler will not be invoked from within this function. On
  867. * immediate completion, invocation of the handler will be performed in a
  868. * manner equivalent to using asio::post().
  869. *
  870. * @par Example
  871. * @code
  872. * void connect_handler(const asio::error_code& error)
  873. * {
  874. * if (!error)
  875. * {
  876. * // Connect succeeded.
  877. * }
  878. * }
  879. *
  880. * ...
  881. *
  882. * asio::ip::tcp::socket socket(my_context);
  883. * asio::ip::tcp::endpoint endpoint(
  884. * asio::ip::address::from_string("1.2.3.4"), 12345);
  885. * socket.async_connect(endpoint, connect_handler);
  886. * @endcode
  887. */
  888. template <typename ConnectHandler>
  889. ASIO_INITFN_RESULT_TYPE(ConnectHandler,
  890. void (asio::error_code))
  891. async_connect(const endpoint_type& peer_endpoint,
  892. ASIO_MOVE_ARG(ConnectHandler) handler)
  893. {
  894. asio::error_code open_ec;
  895. if (!is_open())
  896. {
  897. const protocol_type protocol = peer_endpoint.protocol();
  898. impl_.get_service().open(impl_.get_implementation(), protocol, open_ec);
  899. }
  900. return async_initiate<ConnectHandler, void (asio::error_code)>(
  901. initiate_async_connect(), handler, this, peer_endpoint, open_ec);
  902. }
  903. /// Set an option on the socket.
  904. /**
  905. * This function is used to set an option on the socket.
  906. *
  907. * @param option The new option value to be set on the socket.
  908. *
  909. * @throws asio::system_error Thrown on failure.
  910. *
  911. * @sa SettableSocketOption @n
  912. * asio::socket_base::broadcast @n
  913. * asio::socket_base::do_not_route @n
  914. * asio::socket_base::keep_alive @n
  915. * asio::socket_base::linger @n
  916. * asio::socket_base::receive_buffer_size @n
  917. * asio::socket_base::receive_low_watermark @n
  918. * asio::socket_base::reuse_address @n
  919. * asio::socket_base::send_buffer_size @n
  920. * asio::socket_base::send_low_watermark @n
  921. * asio::ip::multicast::join_group @n
  922. * asio::ip::multicast::leave_group @n
  923. * asio::ip::multicast::enable_loopback @n
  924. * asio::ip::multicast::outbound_interface @n
  925. * asio::ip::multicast::hops @n
  926. * asio::ip::tcp::no_delay
  927. *
  928. * @par Example
  929. * Setting the IPPROTO_TCP/TCP_NODELAY option:
  930. * @code
  931. * asio::ip::tcp::socket socket(my_context);
  932. * ...
  933. * asio::ip::tcp::no_delay option(true);
  934. * socket.set_option(option);
  935. * @endcode
  936. */
  937. template <typename SettableSocketOption>
  938. void set_option(const SettableSocketOption& option)
  939. {
  940. asio::error_code ec;
  941. impl_.get_service().set_option(impl_.get_implementation(), option, ec);
  942. asio::detail::throw_error(ec, "set_option");
  943. }
  944. /// Set an option on the socket.
  945. /**
  946. * This function is used to set an option on the socket.
  947. *
  948. * @param option The new option value to be set on the socket.
  949. *
  950. * @param ec Set to indicate what error occurred, if any.
  951. *
  952. * @sa SettableSocketOption @n
  953. * asio::socket_base::broadcast @n
  954. * asio::socket_base::do_not_route @n
  955. * asio::socket_base::keep_alive @n
  956. * asio::socket_base::linger @n
  957. * asio::socket_base::receive_buffer_size @n
  958. * asio::socket_base::receive_low_watermark @n
  959. * asio::socket_base::reuse_address @n
  960. * asio::socket_base::send_buffer_size @n
  961. * asio::socket_base::send_low_watermark @n
  962. * asio::ip::multicast::join_group @n
  963. * asio::ip::multicast::leave_group @n
  964. * asio::ip::multicast::enable_loopback @n
  965. * asio::ip::multicast::outbound_interface @n
  966. * asio::ip::multicast::hops @n
  967. * asio::ip::tcp::no_delay
  968. *
  969. * @par Example
  970. * Setting the IPPROTO_TCP/TCP_NODELAY option:
  971. * @code
  972. * asio::ip::tcp::socket socket(my_context);
  973. * ...
  974. * asio::ip::tcp::no_delay option(true);
  975. * asio::error_code ec;
  976. * socket.set_option(option, ec);
  977. * if (ec)
  978. * {
  979. * // An error occurred.
  980. * }
  981. * @endcode
  982. */
  983. template <typename SettableSocketOption>
  984. ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option,
  985. asio::error_code& ec)
  986. {
  987. impl_.get_service().set_option(impl_.get_implementation(), option, ec);
  988. ASIO_SYNC_OP_VOID_RETURN(ec);
  989. }
  990. /// Get an option from the socket.
  991. /**
  992. * This function is used to get the current value of an option on the socket.
  993. *
  994. * @param option The option value to be obtained from the socket.
  995. *
  996. * @throws asio::system_error Thrown on failure.
  997. *
  998. * @sa GettableSocketOption @n
  999. * asio::socket_base::broadcast @n
  1000. * asio::socket_base::do_not_route @n
  1001. * asio::socket_base::keep_alive @n
  1002. * asio::socket_base::linger @n
  1003. * asio::socket_base::receive_buffer_size @n
  1004. * asio::socket_base::receive_low_watermark @n
  1005. * asio::socket_base::reuse_address @n
  1006. * asio::socket_base::send_buffer_size @n
  1007. * asio::socket_base::send_low_watermark @n
  1008. * asio::ip::multicast::join_group @n
  1009. * asio::ip::multicast::leave_group @n
  1010. * asio::ip::multicast::enable_loopback @n
  1011. * asio::ip::multicast::outbound_interface @n
  1012. * asio::ip::multicast::hops @n
  1013. * asio::ip::tcp::no_delay
  1014. *
  1015. * @par Example
  1016. * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:
  1017. * @code
  1018. * asio::ip::tcp::socket socket(my_context);
  1019. * ...
  1020. * asio::ip::tcp::socket::keep_alive option;
  1021. * socket.get_option(option);
  1022. * bool is_set = option.value();
  1023. * @endcode
  1024. */
  1025. template <typename GettableSocketOption>
  1026. void get_option(GettableSocketOption& option) const
  1027. {
  1028. asio::error_code ec;
  1029. impl_.get_service().get_option(impl_.get_implementation(), option, ec);
  1030. asio::detail::throw_error(ec, "get_option");
  1031. }
  1032. /// Get an option from the socket.
  1033. /**
  1034. * This function is used to get the current value of an option on the socket.
  1035. *
  1036. * @param option The option value to be obtained from the socket.
  1037. *
  1038. * @param ec Set to indicate what error occurred, if any.
  1039. *
  1040. * @sa GettableSocketOption @n
  1041. * asio::socket_base::broadcast @n
  1042. * asio::socket_base::do_not_route @n
  1043. * asio::socket_base::keep_alive @n
  1044. * asio::socket_base::linger @n
  1045. * asio::socket_base::receive_buffer_size @n
  1046. * asio::socket_base::receive_low_watermark @n
  1047. * asio::socket_base::reuse_address @n
  1048. * asio::socket_base::send_buffer_size @n
  1049. * asio::socket_base::send_low_watermark @n
  1050. * asio::ip::multicast::join_group @n
  1051. * asio::ip::multicast::leave_group @n
  1052. * asio::ip::multicast::enable_loopback @n
  1053. * asio::ip::multicast::outbound_interface @n
  1054. * asio::ip::multicast::hops @n
  1055. * asio::ip::tcp::no_delay
  1056. *
  1057. * @par Example
  1058. * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option:
  1059. * @code
  1060. * asio::ip::tcp::socket socket(my_context);
  1061. * ...
  1062. * asio::ip::tcp::socket::keep_alive option;
  1063. * asio::error_code ec;
  1064. * socket.get_option(option, ec);
  1065. * if (ec)
  1066. * {
  1067. * // An error occurred.
  1068. * }
  1069. * bool is_set = option.value();
  1070. * @endcode
  1071. */
  1072. template <typename GettableSocketOption>
  1073. ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option,
  1074. asio::error_code& ec) const
  1075. {
  1076. impl_.get_service().get_option(impl_.get_implementation(), option, ec);
  1077. ASIO_SYNC_OP_VOID_RETURN(ec);
  1078. }
  1079. /// Perform an IO control command on the socket.
  1080. /**
  1081. * This function is used to execute an IO control command on the socket.
  1082. *
  1083. * @param command The IO control command to be performed on the socket.
  1084. *
  1085. * @throws asio::system_error Thrown on failure.
  1086. *
  1087. * @sa IoControlCommand @n
  1088. * asio::socket_base::bytes_readable @n
  1089. * asio::socket_base::non_blocking_io
  1090. *
  1091. * @par Example
  1092. * Getting the number of bytes ready to read:
  1093. * @code
  1094. * asio::ip::tcp::socket socket(my_context);
  1095. * ...
  1096. * asio::ip::tcp::socket::bytes_readable command;
  1097. * socket.io_control(command);
  1098. * std::size_t bytes_readable = command.get();
  1099. * @endcode
  1100. */
  1101. template <typename IoControlCommand>
  1102. void io_control(IoControlCommand& command)
  1103. {
  1104. asio::error_code ec;
  1105. impl_.get_service().io_control(impl_.get_implementation(), command, ec);
  1106. asio::detail::throw_error(ec, "io_control");
  1107. }
  1108. /// Perform an IO control command on the socket.
  1109. /**
  1110. * This function is used to execute an IO control command on the socket.
  1111. *
  1112. * @param command The IO control command to be performed on the socket.
  1113. *
  1114. * @param ec Set to indicate what error occurred, if any.
  1115. *
  1116. * @sa IoControlCommand @n
  1117. * asio::socket_base::bytes_readable @n
  1118. * asio::socket_base::non_blocking_io
  1119. *
  1120. * @par Example
  1121. * Getting the number of bytes ready to read:
  1122. * @code
  1123. * asio::ip::tcp::socket socket(my_context);
  1124. * ...
  1125. * asio::ip::tcp::socket::bytes_readable command;
  1126. * asio::error_code ec;
  1127. * socket.io_control(command, ec);
  1128. * if (ec)
  1129. * {
  1130. * // An error occurred.
  1131. * }
  1132. * std::size_t bytes_readable = command.get();
  1133. * @endcode
  1134. */
  1135. template <typename IoControlCommand>
  1136. ASIO_SYNC_OP_VOID io_control(IoControlCommand& command,
  1137. asio::error_code& ec)
  1138. {
  1139. impl_.get_service().io_control(impl_.get_implementation(), command, ec);
  1140. ASIO_SYNC_OP_VOID_RETURN(ec);
  1141. }
  1142. /// Gets the non-blocking mode of the socket.
  1143. /**
  1144. * @returns @c true if the socket's synchronous operations will fail with
  1145. * asio::error::would_block if they are unable to perform the requested
  1146. * operation immediately. If @c false, synchronous operations will block
  1147. * until complete.
  1148. *
  1149. * @note The non-blocking mode has no effect on the behaviour of asynchronous
  1150. * operations. Asynchronous operations will never fail with the error
  1151. * asio::error::would_block.
  1152. */
  1153. bool non_blocking() const
  1154. {
  1155. return impl_.get_service().non_blocking(impl_.get_implementation());
  1156. }
  1157. /// Sets the non-blocking mode of the socket.
  1158. /**
  1159. * @param mode If @c true, the socket's synchronous operations will fail with
  1160. * asio::error::would_block if they are unable to perform the requested
  1161. * operation immediately. If @c false, synchronous operations will block
  1162. * until complete.
  1163. *
  1164. * @throws asio::system_error Thrown on failure.
  1165. *
  1166. * @note The non-blocking mode has no effect on the behaviour of asynchronous
  1167. * operations. Asynchronous operations will never fail with the error
  1168. * asio::error::would_block.
  1169. */
  1170. void non_blocking(bool mode)
  1171. {
  1172. asio::error_code ec;
  1173. impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec);
  1174. asio::detail::throw_error(ec, "non_blocking");
  1175. }
  1176. /// Sets the non-blocking mode of the socket.
  1177. /**
  1178. * @param mode If @c true, the socket's synchronous operations will fail with
  1179. * asio::error::would_block if they are unable to perform the requested
  1180. * operation immediately. If @c false, synchronous operations will block
  1181. * until complete.
  1182. *
  1183. * @param ec Set to indicate what error occurred, if any.
  1184. *
  1185. * @note The non-blocking mode has no effect on the behaviour of asynchronous
  1186. * operations. Asynchronous operations will never fail with the error
  1187. * asio::error::would_block.
  1188. */
  1189. ASIO_SYNC_OP_VOID non_blocking(
  1190. bool mode, asio::error_code& ec)
  1191. {
  1192. impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec);
  1193. ASIO_SYNC_OP_VOID_RETURN(ec);
  1194. }
  1195. /// Gets the non-blocking mode of the native socket implementation.
  1196. /**
  1197. * This function is used to retrieve the non-blocking mode of the underlying
  1198. * native socket. This mode has no effect on the behaviour of the socket
  1199. * object's synchronous operations.
  1200. *
  1201. * @returns @c true if the underlying socket is in non-blocking mode and
  1202. * direct system calls may fail with asio::error::would_block (or the
  1203. * equivalent system error).
  1204. *
  1205. * @note The current non-blocking mode is cached by the socket object.
  1206. * Consequently, the return value may be incorrect if the non-blocking mode
  1207. * was set directly on the native socket.
  1208. *
  1209. * @par Example
  1210. * This function is intended to allow the encapsulation of arbitrary
  1211. * non-blocking system calls as asynchronous operations, in a way that is
  1212. * transparent to the user of the socket object. The following example
  1213. * illustrates how Linux's @c sendfile system call might be encapsulated:
  1214. * @code template <typename Handler>
  1215. * struct sendfile_op
  1216. * {
  1217. * tcp::socket& sock_;
  1218. * int fd_;
  1219. * Handler handler_;
  1220. * off_t offset_;
  1221. * std::size_t total_bytes_transferred_;
  1222. *
  1223. * // Function call operator meeting WriteHandler requirements.
  1224. * // Used as the handler for the async_write_some operation.
  1225. * void operator()(asio::error_code ec, std::size_t)
  1226. * {
  1227. * // Put the underlying socket into non-blocking mode.
  1228. * if (!ec)
  1229. * if (!sock_.native_non_blocking())
  1230. * sock_.native_non_blocking(true, ec);
  1231. *
  1232. * if (!ec)
  1233. * {
  1234. * for (;;)
  1235. * {
  1236. * // Try the system call.
  1237. * errno = 0;
  1238. * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
  1239. * ec = asio::error_code(n < 0 ? errno : 0,
  1240. * asio::error::get_system_category());
  1241. * total_bytes_transferred_ += ec ? 0 : n;
  1242. *
  1243. * // Retry operation immediately if interrupted by signal.
  1244. * if (ec == asio::error::interrupted)
  1245. * continue;
  1246. *
  1247. * // Check if we need to run the operation again.
  1248. * if (ec == asio::error::would_block
  1249. * || ec == asio::error::try_again)
  1250. * {
  1251. * // We have to wait for the socket to become ready again.
  1252. * sock_.async_wait(tcp::socket::wait_write, *this);
  1253. * return;
  1254. * }
  1255. *
  1256. * if (ec || n == 0)
  1257. * {
  1258. * // An error occurred, or we have reached the end of the file.
  1259. * // Either way we must exit the loop so we can call the handler.
  1260. * break;
  1261. * }
  1262. *
  1263. * // Loop around to try calling sendfile again.
  1264. * }
  1265. * }
  1266. *
  1267. * // Pass result back to user's handler.
  1268. * handler_(ec, total_bytes_transferred_);
  1269. * }
  1270. * };
  1271. *
  1272. * template <typename Handler>
  1273. * void async_sendfile(tcp::socket& sock, int fd, Handler h)
  1274. * {
  1275. * sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  1276. * sock.async_wait(tcp::socket::wait_write, op);
  1277. * } @endcode
  1278. */
  1279. bool native_non_blocking() const
  1280. {
  1281. return impl_.get_service().native_non_blocking(impl_.get_implementation());
  1282. }
  1283. /// Sets the non-blocking mode of the native socket implementation.
  1284. /**
  1285. * This function is used to modify the non-blocking mode of the underlying
  1286. * native socket. It has no effect on the behaviour of the socket object's
  1287. * synchronous operations.
  1288. *
  1289. * @param mode If @c true, the underlying socket is put into non-blocking
  1290. * mode and direct system calls may fail with asio::error::would_block
  1291. * (or the equivalent system error).
  1292. *
  1293. * @throws asio::system_error Thrown on failure. If the @c mode is
  1294. * @c false, but the current value of @c non_blocking() is @c true, this
  1295. * function fails with asio::error::invalid_argument, as the
  1296. * combination does not make sense.
  1297. *
  1298. * @par Example
  1299. * This function is intended to allow the encapsulation of arbitrary
  1300. * non-blocking system calls as asynchronous operations, in a way that is
  1301. * transparent to the user of the socket object. The following example
  1302. * illustrates how Linux's @c sendfile system call might be encapsulated:
  1303. * @code template <typename Handler>
  1304. * struct sendfile_op
  1305. * {
  1306. * tcp::socket& sock_;
  1307. * int fd_;
  1308. * Handler handler_;
  1309. * off_t offset_;
  1310. * std::size_t total_bytes_transferred_;
  1311. *
  1312. * // Function call operator meeting WriteHandler requirements.
  1313. * // Used as the handler for the async_write_some operation.
  1314. * void operator()(asio::error_code ec, std::size_t)
  1315. * {
  1316. * // Put the underlying socket into non-blocking mode.
  1317. * if (!ec)
  1318. * if (!sock_.native_non_blocking())
  1319. * sock_.native_non_blocking(true, ec);
  1320. *
  1321. * if (!ec)
  1322. * {
  1323. * for (;;)
  1324. * {
  1325. * // Try the system call.
  1326. * errno = 0;
  1327. * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
  1328. * ec = asio::error_code(n < 0 ? errno : 0,
  1329. * asio::error::get_system_category());
  1330. * total_bytes_transferred_ += ec ? 0 : n;
  1331. *
  1332. * // Retry operation immediately if interrupted by signal.
  1333. * if (ec == asio::error::interrupted)
  1334. * continue;
  1335. *
  1336. * // Check if we need to run the operation again.
  1337. * if (ec == asio::error::would_block
  1338. * || ec == asio::error::try_again)
  1339. * {
  1340. * // We have to wait for the socket to become ready again.
  1341. * sock_.async_wait(tcp::socket::wait_write, *this);
  1342. * return;
  1343. * }
  1344. *
  1345. * if (ec || n == 0)
  1346. * {
  1347. * // An error occurred, or we have reached the end of the file.
  1348. * // Either way we must exit the loop so we can call the handler.
  1349. * break;
  1350. * }
  1351. *
  1352. * // Loop around to try calling sendfile again.
  1353. * }
  1354. * }
  1355. *
  1356. * // Pass result back to user's handler.
  1357. * handler_(ec, total_bytes_transferred_);
  1358. * }
  1359. * };
  1360. *
  1361. * template <typename Handler>
  1362. * void async_sendfile(tcp::socket& sock, int fd, Handler h)
  1363. * {
  1364. * sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  1365. * sock.async_wait(tcp::socket::wait_write, op);
  1366. * } @endcode
  1367. */
  1368. void native_non_blocking(bool mode)
  1369. {
  1370. asio::error_code ec;
  1371. impl_.get_service().native_non_blocking(
  1372. impl_.get_implementation(), mode, ec);
  1373. asio::detail::throw_error(ec, "native_non_blocking");
  1374. }
  1375. /// Sets the non-blocking mode of the native socket implementation.
  1376. /**
  1377. * This function is used to modify the non-blocking mode of the underlying
  1378. * native socket. It has no effect on the behaviour of the socket object's
  1379. * synchronous operations.
  1380. *
  1381. * @param mode If @c true, the underlying socket is put into non-blocking
  1382. * mode and direct system calls may fail with asio::error::would_block
  1383. * (or the equivalent system error).
  1384. *
  1385. * @param ec Set to indicate what error occurred, if any. If the @c mode is
  1386. * @c false, but the current value of @c non_blocking() is @c true, this
  1387. * function fails with asio::error::invalid_argument, as the
  1388. * combination does not make sense.
  1389. *
  1390. * @par Example
  1391. * This function is intended to allow the encapsulation of arbitrary
  1392. * non-blocking system calls as asynchronous operations, in a way that is
  1393. * transparent to the user of the socket object. The following example
  1394. * illustrates how Linux's @c sendfile system call might be encapsulated:
  1395. * @code template <typename Handler>
  1396. * struct sendfile_op
  1397. * {
  1398. * tcp::socket& sock_;
  1399. * int fd_;
  1400. * Handler handler_;
  1401. * off_t offset_;
  1402. * std::size_t total_bytes_transferred_;
  1403. *
  1404. * // Function call operator meeting WriteHandler requirements.
  1405. * // Used as the handler for the async_write_some operation.
  1406. * void operator()(asio::error_code ec, std::size_t)
  1407. * {
  1408. * // Put the underlying socket into non-blocking mode.
  1409. * if (!ec)
  1410. * if (!sock_.native_non_blocking())
  1411. * sock_.native_non_blocking(true, ec);
  1412. *
  1413. * if (!ec)
  1414. * {
  1415. * for (;;)
  1416. * {
  1417. * // Try the system call.
  1418. * errno = 0;
  1419. * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536);
  1420. * ec = asio::error_code(n < 0 ? errno : 0,
  1421. * asio::error::get_system_category());
  1422. * total_bytes_transferred_ += ec ? 0 : n;
  1423. *
  1424. * // Retry operation immediately if interrupted by signal.
  1425. * if (ec == asio::error::interrupted)
  1426. * continue;
  1427. *
  1428. * // Check if we need to run the operation again.
  1429. * if (ec == asio::error::would_block
  1430. * || ec == asio::error::try_again)
  1431. * {
  1432. * // We have to wait for the socket to become ready again.
  1433. * sock_.async_wait(tcp::socket::wait_write, *this);
  1434. * return;
  1435. * }
  1436. *
  1437. * if (ec || n == 0)
  1438. * {
  1439. * // An error occurred, or we have reached the end of the file.
  1440. * // Either way we must exit the loop so we can call the handler.
  1441. * break;
  1442. * }
  1443. *
  1444. * // Loop around to try calling sendfile again.
  1445. * }
  1446. * }
  1447. *
  1448. * // Pass result back to user's handler.
  1449. * handler_(ec, total_bytes_transferred_);
  1450. * }
  1451. * };
  1452. *
  1453. * template <typename Handler>
  1454. * void async_sendfile(tcp::socket& sock, int fd, Handler h)
  1455. * {
  1456. * sendfile_op<Handler> op = { sock, fd, h, 0, 0 };
  1457. * sock.async_wait(tcp::socket::wait_write, op);
  1458. * } @endcode
  1459. */
  1460. ASIO_SYNC_OP_VOID native_non_blocking(
  1461. bool mode, asio::error_code& ec)
  1462. {
  1463. impl_.get_service().native_non_blocking(
  1464. impl_.get_implementation(), mode, ec);
  1465. ASIO_SYNC_OP_VOID_RETURN(ec);
  1466. }
  1467. /// Get the local endpoint of the socket.
  1468. /**
  1469. * This function is used to obtain the locally bound endpoint of the socket.
  1470. *
  1471. * @returns An object that represents the local endpoint of the socket.
  1472. *
  1473. * @throws asio::system_error Thrown on failure.
  1474. *
  1475. * @par Example
  1476. * @code
  1477. * asio::ip::tcp::socket socket(my_context);
  1478. * ...
  1479. * asio::ip::tcp::endpoint endpoint = socket.local_endpoint();
  1480. * @endcode
  1481. */
  1482. endpoint_type local_endpoint() const
  1483. {
  1484. asio::error_code ec;
  1485. endpoint_type ep = impl_.get_service().local_endpoint(
  1486. impl_.get_implementation(), ec);
  1487. asio::detail::throw_error(ec, "local_endpoint");
  1488. return ep;
  1489. }
  1490. /// Get the local endpoint of the socket.
  1491. /**
  1492. * This function is used to obtain the locally bound endpoint of the socket.
  1493. *
  1494. * @param ec Set to indicate what error occurred, if any.
  1495. *
  1496. * @returns An object that represents the local endpoint of the socket.
  1497. * Returns a default-constructed endpoint object if an error occurred.
  1498. *
  1499. * @par Example
  1500. * @code
  1501. * asio::ip::tcp::socket socket(my_context);
  1502. * ...
  1503. * asio::error_code ec;
  1504. * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec);
  1505. * if (ec)
  1506. * {
  1507. * // An error occurred.
  1508. * }
  1509. * @endcode
  1510. */
  1511. endpoint_type local_endpoint(asio::error_code& ec) const
  1512. {
  1513. return impl_.get_service().local_endpoint(impl_.get_implementation(), ec);
  1514. }
  1515. /// Get the remote endpoint of the socket.
  1516. /**
  1517. * This function is used to obtain the remote endpoint of the socket.
  1518. *
  1519. * @returns An object that represents the remote endpoint of the socket.
  1520. *
  1521. * @throws asio::system_error Thrown on failure.
  1522. *
  1523. * @par Example
  1524. * @code
  1525. * asio::ip::tcp::socket socket(my_context);
  1526. * ...
  1527. * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();
  1528. * @endcode
  1529. */
  1530. endpoint_type remote_endpoint() const
  1531. {
  1532. asio::error_code ec;
  1533. endpoint_type ep = impl_.get_service().remote_endpoint(
  1534. impl_.get_implementation(), ec);
  1535. asio::detail::throw_error(ec, "remote_endpoint");
  1536. return ep;
  1537. }
  1538. /// Get the remote endpoint of the socket.
  1539. /**
  1540. * This function is used to obtain the remote endpoint of the socket.
  1541. *
  1542. * @param ec Set to indicate what error occurred, if any.
  1543. *
  1544. * @returns An object that represents the remote endpoint of the socket.
  1545. * Returns a default-constructed endpoint object if an error occurred.
  1546. *
  1547. * @par Example
  1548. * @code
  1549. * asio::ip::tcp::socket socket(my_context);
  1550. * ...
  1551. * asio::error_code ec;
  1552. * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
  1553. * if (ec)
  1554. * {
  1555. * // An error occurred.
  1556. * }
  1557. * @endcode
  1558. */
  1559. endpoint_type remote_endpoint(asio::error_code& ec) const
  1560. {
  1561. return impl_.get_service().remote_endpoint(impl_.get_implementation(), ec);
  1562. }
  1563. /// Disable sends or receives on the socket.
  1564. /**
  1565. * This function is used to disable send operations, receive operations, or
  1566. * both.
  1567. *
  1568. * @param what Determines what types of operation will no longer be allowed.
  1569. *
  1570. * @throws asio::system_error Thrown on failure.
  1571. *
  1572. * @par Example
  1573. * Shutting down the send side of the socket:
  1574. * @code
  1575. * asio::ip::tcp::socket socket(my_context);
  1576. * ...
  1577. * socket.shutdown(asio::ip::tcp::socket::shutdown_send);
  1578. * @endcode
  1579. */
  1580. void shutdown(shutdown_type what)
  1581. {
  1582. asio::error_code ec;
  1583. impl_.get_service().shutdown(impl_.get_implementation(), what, ec);
  1584. asio::detail::throw_error(ec, "shutdown");
  1585. }
  1586. /// Disable sends or receives on the socket.
  1587. /**
  1588. * This function is used to disable send operations, receive operations, or
  1589. * both.
  1590. *
  1591. * @param what Determines what types of operation will no longer be allowed.
  1592. *
  1593. * @param ec Set to indicate what error occurred, if any.
  1594. *
  1595. * @par Example
  1596. * Shutting down the send side of the socket:
  1597. * @code
  1598. * asio::ip::tcp::socket socket(my_context);
  1599. * ...
  1600. * asio::error_code ec;
  1601. * socket.shutdown(asio::ip::tcp::socket::shutdown_send, ec);
  1602. * if (ec)
  1603. * {
  1604. * // An error occurred.
  1605. * }
  1606. * @endcode
  1607. */
  1608. ASIO_SYNC_OP_VOID shutdown(shutdown_type what,
  1609. asio::error_code& ec)
  1610. {
  1611. impl_.get_service().shutdown(impl_.get_implementation(), what, ec);
  1612. ASIO_SYNC_OP_VOID_RETURN(ec);
  1613. }
  1614. /// Wait for the socket to become ready to read, ready to write, or to have
  1615. /// pending error conditions.
  1616. /**
  1617. * This function is used to perform a blocking wait for a socket to enter
  1618. * a ready to read, write or error condition state.
  1619. *
  1620. * @param w Specifies the desired socket state.
  1621. *
  1622. * @par Example
  1623. * Waiting for a socket to become readable.
  1624. * @code
  1625. * asio::ip::tcp::socket socket(my_context);
  1626. * ...
  1627. * socket.wait(asio::ip::tcp::socket::wait_read);
  1628. * @endcode
  1629. */
  1630. void wait(wait_type w)
  1631. {
  1632. asio::error_code ec;
  1633. impl_.get_service().wait(impl_.get_implementation(), w, ec);
  1634. asio::detail::throw_error(ec, "wait");
  1635. }
  1636. /// Wait for the socket to become ready to read, ready to write, or to have
  1637. /// pending error conditions.
  1638. /**
  1639. * This function is used to perform a blocking wait for a socket to enter
  1640. * a ready to read, write or error condition state.
  1641. *
  1642. * @param w Specifies the desired socket state.
  1643. *
  1644. * @param ec Set to indicate what error occurred, if any.
  1645. *
  1646. * @par Example
  1647. * Waiting for a socket to become readable.
  1648. * @code
  1649. * asio::ip::tcp::socket socket(my_context);
  1650. * ...
  1651. * asio::error_code ec;
  1652. * socket.wait(asio::ip::tcp::socket::wait_read, ec);
  1653. * @endcode
  1654. */
  1655. ASIO_SYNC_OP_VOID wait(wait_type w, asio::error_code& ec)
  1656. {
  1657. impl_.get_service().wait(impl_.get_implementation(), w, ec);
  1658. ASIO_SYNC_OP_VOID_RETURN(ec);
  1659. }
  1660. /// Asynchronously wait for the socket to become ready to read, ready to
  1661. /// write, or to have pending error conditions.
  1662. /**
  1663. * This function is used to perform an asynchronous wait for a socket to enter
  1664. * a ready to read, write or error condition state.
  1665. *
  1666. * @param w Specifies the desired socket state.
  1667. *
  1668. * @param handler The handler to be called when the wait operation completes.
  1669. * Copies will be made of the handler as required. The function signature of
  1670. * the handler must be:
  1671. * @code void handler(
  1672. * const asio::error_code& error // Result of operation
  1673. * ); @endcode
  1674. * Regardless of whether the asynchronous operation completes immediately or
  1675. * not, the handler will not be invoked from within this function. On
  1676. * immediate completion, invocation of the handler will be performed in a
  1677. * manner equivalent to using asio::post().
  1678. *
  1679. * @par Example
  1680. * @code
  1681. * void wait_handler(const asio::error_code& error)
  1682. * {
  1683. * if (!error)
  1684. * {
  1685. * // Wait succeeded.
  1686. * }
  1687. * }
  1688. *
  1689. * ...
  1690. *
  1691. * asio::ip::tcp::socket socket(my_context);
  1692. * ...
  1693. * socket.async_wait(asio::ip::tcp::socket::wait_read, wait_handler);
  1694. * @endcode
  1695. */
  1696. template <typename WaitHandler>
  1697. ASIO_INITFN_RESULT_TYPE(WaitHandler,
  1698. void (asio::error_code))
  1699. async_wait(wait_type w, ASIO_MOVE_ARG(WaitHandler) handler)
  1700. {
  1701. return async_initiate<WaitHandler, void (asio::error_code)>(
  1702. initiate_async_wait(), handler, this, w);
  1703. }
  1704. protected:
  1705. /// Protected destructor to prevent deletion through this type.
  1706. /**
  1707. * This function destroys the socket, cancelling any outstanding asynchronous
  1708. * operations associated with the socket as if by calling @c cancel.
  1709. */
  1710. ~basic_socket()
  1711. {
  1712. }
  1713. #if defined(ASIO_WINDOWS_RUNTIME)
  1714. detail::io_object_impl<
  1715. detail::null_socket_service<Protocol>, Executor> impl_;
  1716. #elif defined(ASIO_HAS_IOCP)
  1717. detail::io_object_impl<
  1718. detail::win_iocp_socket_service<Protocol>, Executor> impl_;
  1719. #else
  1720. detail::io_object_impl<
  1721. detail::reactive_socket_service<Protocol>, Executor> impl_;
  1722. #endif
  1723. private:
  1724. // Disallow copying and assignment.
  1725. basic_socket(const basic_socket&) ASIO_DELETED;
  1726. basic_socket& operator=(const basic_socket&) ASIO_DELETED;
  1727. struct initiate_async_connect
  1728. {
  1729. template <typename ConnectHandler>
  1730. void operator()(ASIO_MOVE_ARG(ConnectHandler) handler,
  1731. basic_socket* self, const endpoint_type& peer_endpoint,
  1732. const asio::error_code& open_ec) const
  1733. {
  1734. // If you get an error on the following line it means that your handler
  1735. // does not meet the documented type requirements for a ConnectHandler.
  1736. ASIO_CONNECT_HANDLER_CHECK(ConnectHandler, handler) type_check;
  1737. if (open_ec)
  1738. {
  1739. asio::post(self->impl_.get_executor(),
  1740. asio::detail::bind_handler(
  1741. ASIO_MOVE_CAST(ConnectHandler)(handler), open_ec));
  1742. }
  1743. else
  1744. {
  1745. detail::non_const_lvalue<ConnectHandler> handler2(handler);
  1746. self->impl_.get_service().async_connect(
  1747. self->impl_.get_implementation(), peer_endpoint,
  1748. handler2.value, self->impl_.get_implementation_executor());
  1749. }
  1750. }
  1751. };
  1752. struct initiate_async_wait
  1753. {
  1754. template <typename WaitHandler>
  1755. void operator()(ASIO_MOVE_ARG(WaitHandler) handler,
  1756. basic_socket* self, wait_type w) const
  1757. {
  1758. // If you get an error on the following line it means that your handler
  1759. // does not meet the documented type requirements for a WaitHandler.
  1760. ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check;
  1761. detail::non_const_lvalue<WaitHandler> handler2(handler);
  1762. self->impl_.get_service().async_wait(
  1763. self->impl_.get_implementation(), w, handler2.value,
  1764. self->impl_.get_implementation_executor());
  1765. }
  1766. };
  1767. };
  1768. } // namespace asio
  1769. #include "asio/detail/pop_options.hpp"
  1770. #endif // ASIO_BASIC_SOCKET_HPP