udp_send_cp.hpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. /*
  2. * Copyright (c) 2017-2023 zhllxt
  3. *
  4. * author : zhllxt
  5. * email : 37792738@qq.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 __ASIO2_UDP_SEND_COMPONENT_HPP__
  11. #define __ASIO2_UDP_SEND_COMPONENT_HPP__
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. #pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <cstdint>
  16. #include <memory>
  17. #include <functional>
  18. #include <string>
  19. #include <future>
  20. #include <queue>
  21. #include <tuple>
  22. #include <utility>
  23. #include <string_view>
  24. #include <asio2/base/iopool.hpp>
  25. #include <asio2/base/define.hpp>
  26. #include <asio2/base/detail/util.hpp>
  27. #include <asio2/base/detail/function_traits.hpp>
  28. #include <asio2/base/detail/buffer_wrap.hpp>
  29. #include <asio2/base/impl/data_persistence_cp.hpp>
  30. namespace asio2::detail
  31. {
  32. ASIO2_CLASS_FORWARD_DECLARE_BASE;
  33. template<class derived_t, class args_t>
  34. class udp_send_cp : public data_persistence_cp<derived_t, args_t>
  35. {
  36. ASIO2_CLASS_FRIEND_DECLARE_BASE;
  37. public:
  38. /**
  39. * @brief constructor
  40. */
  41. udp_send_cp() noexcept {}
  42. /**
  43. * @brief destructor
  44. */
  45. ~udp_send_cp() = default;
  46. public:
  47. /**
  48. * @brief Asynchronous send data,supporting multi data formats,
  49. * see asio::buffer(...) in /asio/buffer.hpp
  50. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  51. * use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
  52. * PodType * : async_send("abc");
  53. * PodType (&data)[N] : double m[10]; async_send(m);
  54. * std::array<PodType, N> : std::array<int,10> m; async_send(m);
  55. * std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
  56. * std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
  57. */
  58. template<typename String, typename StrOrInt, class DataT>
  59. inline typename std::enable_if_t<!std::is_same_v<detail::remove_cvref_t<String>,
  60. asio::ip::udp::endpoint>, void>
  61. async_send(String&& host, StrOrInt&& port, DataT&& data) noexcept
  62. {
  63. derived_t& derive = static_cast<derived_t&>(*this);
  64. detail::integer_add_sub_guard asg(derive.io_->pending());
  65. // We must ensure that there is only one operation to send data
  66. // at the same time,otherwise may be cause crash.
  67. derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
  68. derive._data_persistence(std::forward<DataT>(data)),
  69. [](const error_code&, std::size_t) mutable {});
  70. }
  71. /**
  72. * @brief Asynchronous send data
  73. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  74. * PodType * : async_send("abc");
  75. */
  76. template<typename String, typename StrOrInt, class CharT, class Traits = std::char_traits<CharT>>
  77. inline typename std::enable_if_t<!std::is_same_v<detail::remove_cvref_t<String>,
  78. asio::ip::udp::endpoint> && detail::is_char_v<CharT>, void>
  79. async_send(String&& host, StrOrInt&& port, CharT* s) noexcept
  80. {
  81. derived_t& derive = static_cast<derived_t&>(*this);
  82. derive.async_send(std::forward<String>(host), std::forward<StrOrInt>(port),
  83. s, s ? Traits::length(s) : 0);
  84. }
  85. /**
  86. * @brief Asynchronous send data
  87. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  88. * PodType (&data)[N] : double m[10]; async_send(m,5);
  89. */
  90. template<typename String, typename StrOrInt, class CharT, class SizeT>
  91. inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
  92. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, void>
  93. async_send(String&& host, StrOrInt&& port, CharT * s, SizeT count) noexcept
  94. {
  95. derived_t& derive = static_cast<derived_t&>(*this);
  96. if (!s)
  97. {
  98. set_last_error(asio::error::invalid_argument);
  99. return;
  100. }
  101. detail::integer_add_sub_guard asg(derive.io_->pending());
  102. // We must ensure that there is only one operation to send data
  103. // at the same time,otherwise may be cause crash.
  104. derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
  105. derive._data_persistence(s, count), [](const error_code&, std::size_t) mutable {});
  106. }
  107. /**
  108. * @brief Asynchronous send data,supporting multi data formats,
  109. * see asio::buffer(...) in /asio/buffer.hpp
  110. * use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
  111. * the pair.first save the send result error_code,the pair.second save the sent_bytes.
  112. * note : Do not call this function in any listener callback function like this:
  113. * auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
  114. * the future.get() will never return.
  115. * PodType * : async_send("abc");
  116. * PodType (&data)[N] : double m[10]; async_send(m);
  117. * std::array<PodType, N> : std::array<int,10> m; async_send(m);
  118. * std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
  119. * std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
  120. */
  121. template<typename String, typename StrOrInt, class DataT>
  122. inline typename std::enable_if_t<
  123. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>,
  124. std::future<std::pair<error_code, std::size_t>>>
  125. async_send(String&& host, StrOrInt&& port, DataT&& data, asio::use_future_t<>)
  126. {
  127. derived_t& derive = static_cast<derived_t&>(*this);
  128. detail::integer_add_sub_guard asg(derive.io_->pending());
  129. std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
  130. std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
  131. std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
  132. derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
  133. derive._data_persistence(std::forward<DataT>(data)),
  134. [promise = std::move(promise)](const error_code& ec, std::size_t bytes_sent) mutable
  135. {
  136. // if multiple addresses is resolved for the host and port, then the promise
  137. // will set_value many times, then will cause exception
  138. try
  139. {
  140. promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
  141. }
  142. catch (std::future_errc const& e)
  143. {
  144. set_last_error(e);
  145. }
  146. });
  147. return future;
  148. }
  149. /**
  150. * @brief Asynchronous send data
  151. * the pair.first save the send result error_code,the pair.second save the sent_bytes.
  152. * note : Do not call this function in any listener callback function like this:
  153. * auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
  154. * the future.get() will never return.
  155. * PodType * : async_send("abc");
  156. */
  157. template<typename String, typename StrOrInt, class CharT, class Traits = std::char_traits<CharT>>
  158. inline typename std::enable_if_t<
  159. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint> && detail::is_char_v<CharT>,
  160. std::future<std::pair<error_code, std::size_t>>>
  161. async_send(String&& host, StrOrInt&& port, CharT * s, asio::use_future_t<> flag)
  162. {
  163. derived_t& derive = static_cast<derived_t&>(*this);
  164. return derive.async_send(std::forward<String>(host), std::forward<StrOrInt>(port), s,
  165. s ? Traits::length(s) : 0, std::move(flag));
  166. }
  167. /**
  168. * @brief Asynchronous send data
  169. * the pair.first save the send result error_code,the pair.second save the sent_bytes.
  170. * note : Do not call this function in any listener callback function like this:
  171. * auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
  172. * the future.get() will never return.
  173. * PodType (&data)[N] : double m[10]; async_send(m,5);
  174. */
  175. template<typename String, typename StrOrInt, class CharT, class SizeT>
  176. inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
  177. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>,
  178. std::future<std::pair<error_code, std::size_t>>>
  179. async_send(String&& host, StrOrInt&& port, CharT * s, SizeT count, asio::use_future_t<>)
  180. {
  181. derived_t& derive = static_cast<derived_t&>(*this);
  182. detail::integer_add_sub_guard asg(derive.io_->pending());
  183. std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
  184. std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
  185. std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
  186. if (!s)
  187. {
  188. set_last_error(asio::error::invalid_argument);
  189. promise->set_value(std::pair<error_code, std::size_t>(asio::error::invalid_argument, 0));
  190. return future;
  191. }
  192. derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
  193. derive._data_persistence(s, count),
  194. [promise = std::move(promise)](const error_code& ec, std::size_t bytes_sent) mutable
  195. {
  196. // if multiple addresses is resolved for the host and port, then the promise
  197. // will set_value many times, then will cause exception
  198. try
  199. {
  200. promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
  201. }
  202. catch (std::future_errc const& e)
  203. {
  204. set_last_error(e);
  205. }
  206. });
  207. return future;
  208. }
  209. /**
  210. * @brief Asynchronous send data,supporting multi data formats,
  211. * see asio::buffer(...) in /asio/buffer.hpp
  212. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  213. * use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
  214. * PodType * : async_send("abc");
  215. * PodType (&data)[N] : double m[10]; async_send(m);
  216. * std::array<PodType, N> : std::array<int,10> m; async_send(m);
  217. * std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
  218. * std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
  219. * Callback signature : void() or void(std::size_t bytes_sent)
  220. */
  221. template<typename String, typename StrOrInt, class DataT, class Callback>
  222. inline typename std::enable_if_t<is_callable_v<Callback> &&
  223. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, void>
  224. async_send(String&& host, StrOrInt&& port, DataT&& data, Callback&& fn)
  225. {
  226. derived_t& derive = static_cast<derived_t&>(*this);
  227. detail::integer_add_sub_guard asg(derive.io_->pending());
  228. // We must ensure that there is only one operation to send data
  229. // at the same time,otherwise may be cause crash.
  230. derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
  231. derive._data_persistence(std::forward<DataT>(data)),
  232. [fn = std::forward<Callback>(fn)](const error_code&, std::size_t bytes_sent) mutable
  233. {
  234. callback_helper::call(fn, bytes_sent);
  235. });
  236. }
  237. /**
  238. * @brief Asynchronous send data
  239. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  240. * PodType * : async_send("abc");
  241. * Callback signature : void() or void(std::size_t bytes_sent)
  242. */
  243. template<typename String, typename StrOrInt, class Callback, class CharT,
  244. class Traits = std::char_traits<CharT>>
  245. inline typename std::enable_if_t<is_callable_v<Callback> &&
  246. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint> &&
  247. detail::is_char_v<CharT>, void>
  248. async_send(String&& host, StrOrInt&& port, CharT * s, Callback&& fn)
  249. {
  250. derived_t& derive = static_cast<derived_t&>(*this);
  251. derive.async_send(std::forward<String>(host), std::forward<StrOrInt>(port),
  252. s, s ? Traits::length(s) : 0, std::forward<Callback>(fn));
  253. }
  254. /**
  255. * @brief Asynchronous send data
  256. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  257. * PodType (&data)[N] : double m[10]; async_send(m,5);
  258. * Callback signature : void() or void(std::size_t bytes_sent)
  259. */
  260. template<typename String, typename StrOrInt, class Callback, class CharT, class SizeT>
  261. inline typename std::enable_if_t<is_callable_v<Callback> &&
  262. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint> &&
  263. std::is_integral_v<detail::remove_cvref_t<SizeT>>, void>
  264. async_send(String&& host, StrOrInt&& port, CharT * s, SizeT count, Callback&& fn)
  265. {
  266. derived_t& derive = static_cast<derived_t&>(*this);
  267. detail::integer_add_sub_guard asg(derive.io_->pending());
  268. // We must ensure that there is only one operation to send data
  269. // at the same time,otherwise may be cause crash.
  270. //// don't need do this
  271. //if (!s)
  272. //{
  273. // // ...
  274. //}
  275. derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
  276. derive._data_persistence(s, count),
  277. [fn = std::forward<Callback>(fn)](const error_code&, std::size_t bytes_sent) mutable
  278. {
  279. callback_helper::call(fn, bytes_sent);
  280. });
  281. }
  282. public:
  283. /**
  284. * @brief Asynchronous send data,supporting multi data formats,
  285. * see asio::buffer(...) in /asio/buffer.hpp
  286. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  287. * use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
  288. * PodType * : async_send("abc");
  289. * PodType (&data)[N] : double m[10]; async_send(m);
  290. * std::array<PodType, N> : std::array<int,10> m; async_send(m);
  291. * std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
  292. * std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
  293. */
  294. template<class Endpoint, class DataT>
  295. inline typename std::enable_if_t<
  296. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, void>
  297. async_send(Endpoint&& endpoint, DataT&& data) noexcept
  298. {
  299. derived_t& derive = static_cast<derived_t&>(*this);
  300. detail::integer_add_sub_guard asg(derive.io_->pending());
  301. // We must ensure that there is only one operation to send data
  302. // at the same time,otherwise may be cause crash.
  303. derive.push_event(
  304. [&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
  305. data = derive._data_persistence(std::forward<DataT>(data))]
  306. (event_queue_guard<derived_t> g) mutable
  307. {
  308. if (!derive.is_started())
  309. {
  310. set_last_error(asio::error::not_connected);
  311. return;
  312. }
  313. if (id != derive.life_id())
  314. {
  315. set_last_error(asio::error::operation_aborted);
  316. return;
  317. }
  318. clear_last_error();
  319. derive._do_send(endpoint, data, [g = std::move(g)](const error_code&, std::size_t) mutable {});
  320. });
  321. }
  322. /**
  323. * @brief Asynchronous send data
  324. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  325. * PodType * : async_send("abc");
  326. */
  327. template<class Endpoint, class CharT, class Traits = std::char_traits<CharT>>
  328. inline typename std::enable_if_t<
  329. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
  330. detail::is_char_v<CharT>, void>
  331. async_send(Endpoint&& endpoint, CharT * s) noexcept
  332. {
  333. derived_t& derive = static_cast<derived_t&>(*this);
  334. derive.async_send(std::forward<Endpoint>(endpoint), s, s ? Traits::length(s) : 0);
  335. }
  336. /**
  337. * @brief Asynchronous send data
  338. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  339. * PodType (&data)[N] : double m[10]; async_send(m,5);
  340. */
  341. template<class Endpoint, class CharT, class SizeT>
  342. inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
  343. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, void>
  344. async_send(Endpoint&& endpoint, CharT * s, SizeT count) noexcept
  345. {
  346. derived_t& derive = static_cast<derived_t&>(*this);
  347. if (!s)
  348. {
  349. set_last_error(asio::error::invalid_argument);
  350. return;
  351. }
  352. detail::integer_add_sub_guard asg(derive.io_->pending());
  353. // We must ensure that there is only one operation to send data
  354. // at the same time,otherwise may be cause crash.
  355. derive.push_event(
  356. [&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
  357. data = derive._data_persistence(s, count)]
  358. (event_queue_guard<derived_t> g) mutable
  359. {
  360. if (!derive.is_started())
  361. {
  362. set_last_error(asio::error::not_connected);
  363. return;
  364. }
  365. if (id != derive.life_id())
  366. {
  367. set_last_error(asio::error::operation_aborted);
  368. return;
  369. }
  370. clear_last_error();
  371. derive._do_send(endpoint, data, [g = std::move(g)](const error_code&, std::size_t) mutable {});
  372. });
  373. }
  374. /**
  375. * @brief Asynchronous send data,supporting multi data formats,
  376. * see asio::buffer(...) in /asio/buffer.hpp
  377. * use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
  378. * the pair.first save the send result error_code,the pair.second save the sent_bytes.
  379. * note : Do not call this function in any listener callback function like this:
  380. * auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
  381. * the future.get() will never return.
  382. * PodType * : async_send("abc");
  383. * PodType (&data)[N] : double m[10]; async_send(m);
  384. * std::array<PodType, N> : std::array<int,10> m; async_send(m);
  385. * std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
  386. * std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
  387. */
  388. template<class Endpoint, class DataT>
  389. inline typename std::enable_if_t<
  390. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>,
  391. std::future<std::pair<error_code, std::size_t>>>
  392. async_send(Endpoint&& endpoint, DataT&& data, asio::use_future_t<>)
  393. {
  394. derived_t& derive = static_cast<derived_t&>(*this);
  395. detail::integer_add_sub_guard asg(derive.io_->pending());
  396. std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
  397. std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
  398. std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
  399. derive.push_event(
  400. [&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
  401. data = derive._data_persistence(std::forward<DataT>(data)), promise = std::move(promise)]
  402. (event_queue_guard<derived_t> g) mutable
  403. {
  404. if (!derive.is_started())
  405. {
  406. set_last_error(asio::error::not_connected);
  407. promise->set_value(std::pair<error_code, std::size_t>(asio::error::not_connected, 0));
  408. return;
  409. }
  410. if (id != derive.life_id())
  411. {
  412. set_last_error(asio::error::operation_aborted);
  413. promise->set_value(std::pair<error_code, std::size_t>(asio::error::operation_aborted, 0));
  414. return;
  415. }
  416. clear_last_error();
  417. derive._do_send(endpoint, data, [&promise, g = std::move(g)]
  418. (const error_code& ec, std::size_t bytes_sent) mutable
  419. {
  420. promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
  421. });
  422. });
  423. return future;
  424. }
  425. /**
  426. * @brief Asynchronous send data
  427. * the pair.first save the send result error_code,the pair.second save the sent_bytes.
  428. * note : Do not call this function in any listener callback function like this:
  429. * auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
  430. * the future.get() will never return.
  431. * PodType * : async_send("abc");
  432. */
  433. template<class Endpoint, class CharT, class Traits = std::char_traits<CharT>>
  434. inline typename std::enable_if_t<
  435. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> && detail::is_char_v<CharT>,
  436. std::future<std::pair<error_code, std::size_t>>>
  437. async_send(Endpoint&& endpoint, CharT * s, asio::use_future_t<> flag)
  438. {
  439. derived_t& derive = static_cast<derived_t&>(*this);
  440. return derive.async_send(std::forward<Endpoint>(endpoint), s,
  441. s ? Traits::length(s) : 0, std::move(flag));
  442. }
  443. /**
  444. * @brief Asynchronous send data
  445. * the pair.first save the send result error_code,the pair.second save the sent_bytes.
  446. * note : Do not call this function in any listener callback function like this:
  447. * auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
  448. * the future.get() will never return.
  449. * PodType (&data)[N] : double m[10]; async_send(m,5);
  450. */
  451. template<class Endpoint, class CharT, class SizeT>
  452. inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
  453. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>,
  454. std::future<std::pair<error_code, std::size_t>>>
  455. async_send(Endpoint&& endpoint, CharT * s, SizeT count, asio::use_future_t<>)
  456. {
  457. derived_t& derive = static_cast<derived_t&>(*this);
  458. detail::integer_add_sub_guard asg(derive.io_->pending());
  459. std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
  460. std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
  461. std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
  462. if (!s)
  463. {
  464. set_last_error(asio::error::invalid_argument);
  465. promise->set_value(std::pair<error_code, std::size_t>(asio::error::invalid_argument, 0));
  466. return future;
  467. }
  468. derive.push_event(
  469. [&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
  470. data = derive._data_persistence(s, count), promise = std::move(promise)]
  471. (event_queue_guard<derived_t> g) mutable
  472. {
  473. if (!derive.is_started())
  474. {
  475. set_last_error(asio::error::not_connected);
  476. promise->set_value(std::pair<error_code, std::size_t>(asio::error::not_connected, 0));
  477. return;
  478. }
  479. if (id != derive.life_id())
  480. {
  481. set_last_error(asio::error::operation_aborted);
  482. promise->set_value(std::pair<error_code, std::size_t>(asio::error::operation_aborted, 0));
  483. return;
  484. }
  485. clear_last_error();
  486. derive._do_send(endpoint, data, [&promise, g = std::move(g)]
  487. (const error_code& ec, std::size_t bytes_sent) mutable
  488. {
  489. promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
  490. });
  491. });
  492. return future;
  493. }
  494. /**
  495. * @brief Asynchronous send data,supporting multi data formats,
  496. * see asio::buffer(...) in /asio/buffer.hpp
  497. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  498. * use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
  499. * PodType * : async_send("abc");
  500. * PodType (&data)[N] : double m[10]; async_send(m);
  501. * std::array<PodType, N> : std::array<int,10> m; async_send(m);
  502. * std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
  503. * std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
  504. * Callback signature : void() or void(std::size_t bytes_sent)
  505. */
  506. template<class Endpoint, class DataT, class Callback>
  507. inline typename std::enable_if_t<is_callable_v<Callback> &&
  508. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, void>
  509. async_send(Endpoint&& endpoint, DataT&& data, Callback&& fn)
  510. {
  511. derived_t& derive = static_cast<derived_t&>(*this);
  512. detail::integer_add_sub_guard asg(derive.io_->pending());
  513. // We must ensure that there is only one operation to send data
  514. // at the same time,otherwise may be cause crash.
  515. derive.push_event(
  516. [&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
  517. data = derive._data_persistence(std::forward<DataT>(data)), fn = std::forward<Callback>(fn)]
  518. (event_queue_guard<derived_t> g) mutable
  519. {
  520. if (!derive.is_started())
  521. {
  522. set_last_error(asio::error::not_connected);
  523. callback_helper::call(fn, 0);
  524. return;
  525. }
  526. if (id != derive.life_id())
  527. {
  528. set_last_error(asio::error::operation_aborted);
  529. callback_helper::call(fn, 0);
  530. return;
  531. }
  532. clear_last_error();
  533. derive._do_send(endpoint, data, [&fn, g = std::move(g)]
  534. (const error_code&, std::size_t bytes_sent) mutable
  535. {
  536. callback_helper::call(fn, bytes_sent);
  537. });
  538. });
  539. }
  540. /**
  541. * @brief Asynchronous send data
  542. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  543. * PodType * : async_send("abc");
  544. * Callback signature : void() or void(std::size_t bytes_sent)
  545. */
  546. template<class Endpoint, class Callback, class CharT, class Traits = std::char_traits<CharT>>
  547. inline typename std::enable_if_t<is_callable_v<Callback> &&
  548. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
  549. detail::is_char_v<CharT>, void>
  550. async_send(Endpoint&& endpoint, CharT * s, Callback&& fn)
  551. {
  552. derived_t& derive = static_cast<derived_t&>(*this);
  553. derive.async_send(std::forward<Endpoint>(endpoint),
  554. s, s ? Traits::length(s) : 0, std::forward<Callback>(fn));
  555. }
  556. /**
  557. * @brief Asynchronous send data
  558. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  559. * PodType (&data)[N] : double m[10]; async_send(m,5);
  560. * Callback signature : void() or void(std::size_t bytes_sent)
  561. */
  562. template<class Endpoint, class Callback, class CharT, class SizeT>
  563. inline typename std::enable_if_t<is_callable_v<Callback> &&
  564. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
  565. std::is_integral_v<detail::remove_cvref_t<SizeT>>, void>
  566. async_send(Endpoint&& endpoint, CharT * s, SizeT count, Callback&& fn)
  567. {
  568. derived_t& derive = static_cast<derived_t&>(*this);
  569. detail::integer_add_sub_guard asg(derive.io_->pending());
  570. // We must ensure that there is only one operation to send data
  571. // at the same time,otherwise may be cause crash.
  572. derive.push_event(
  573. [&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
  574. s, data = derive._data_persistence(s, count), fn = std::forward<Callback>(fn)]
  575. (event_queue_guard<derived_t> g) mutable
  576. {
  577. if (!s)
  578. {
  579. set_last_error(asio::error::invalid_argument);
  580. callback_helper::call(fn, 0);
  581. return;
  582. }
  583. if (!derive.is_started())
  584. {
  585. set_last_error(asio::error::not_connected);
  586. callback_helper::call(fn, 0);
  587. return;
  588. }
  589. if (id != derive.life_id())
  590. {
  591. set_last_error(asio::error::operation_aborted);
  592. callback_helper::call(fn, 0);
  593. return;
  594. }
  595. clear_last_error();
  596. derive._do_send(endpoint, data, [&fn, g = std::move(g)]
  597. (const error_code&, std::size_t bytes_sent) mutable
  598. {
  599. callback_helper::call(fn, bytes_sent);
  600. });
  601. });
  602. }
  603. public:
  604. /**
  605. * @brief Synchronous send data,supporting multi data formats,
  606. * see asio::buffer(...) in /asio/buffer.hpp
  607. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  608. * Note : If this function is called in communication thread, it will degenerates into async_send
  609. * and the return value is 0, you can use asio2::get_last_error() to check whether the
  610. * send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
  611. * means success, otherwise failed.
  612. * use like this : std::string m; send(std::move(m)); can reducing memory allocation.
  613. * PodType * : send("abc");
  614. * PodType (&data)[N] : double m[10]; send(m);
  615. * std::array<PodType, N> : std::array<int,10> m; send(m);
  616. * std::vector<PodType, Allocator> : std::vector<float> m; send(m);
  617. * std::basic_string<Elem, Traits, Allocator> : std::string m; send(m);
  618. */
  619. template<typename String, typename StrOrInt, class DataT>
  620. inline typename std::enable_if_t<
  621. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, std::size_t>
  622. send(String&& host, StrOrInt&& port, DataT&& data)
  623. {
  624. derived_t& derive = static_cast<derived_t&>(*this);
  625. std::future<std::pair<error_code, std::size_t>> future = derive.async_send(
  626. std::forward<String>(host), std::forward<StrOrInt>(port),
  627. std::forward<DataT>(data), asio::use_future);
  628. // Whether we run on the io_context thread
  629. if (derive.io_->running_in_this_thread())
  630. {
  631. std::future_status status = future.wait_for(std::chrono::nanoseconds(0));
  632. // async_send failed.
  633. if (status == std::future_status::ready)
  634. {
  635. set_last_error(future.get().first);
  636. return std::size_t(0);
  637. }
  638. // async_send success.
  639. else
  640. {
  641. set_last_error(asio::error::in_progress);
  642. return std::size_t(0);
  643. }
  644. }
  645. std::pair<error_code, std::size_t> pair = future.get();
  646. set_last_error(pair.first);
  647. return pair.second;
  648. }
  649. /**
  650. * @brief Synchronous send data
  651. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  652. * Note : If this function is called in communication thread, it will degenerates into async_send
  653. * and the return value is 0, you can use asio2::get_last_error() to check whether the
  654. * send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
  655. * means success, otherwise failed.
  656. * PodType * : send("abc");
  657. */
  658. template<typename String, typename StrOrInt, class CharT, class Traits = std::char_traits<CharT>>
  659. inline typename std::enable_if_t<!std::is_same_v<detail::remove_cvref_t<String>,
  660. asio::ip::udp::endpoint> && detail::is_char_v<CharT>, std::size_t>
  661. send(String&& host, StrOrInt&& port, CharT* s)
  662. {
  663. derived_t& derive = static_cast<derived_t&>(*this);
  664. return derive.send(std::forward<String>(host), std::forward<StrOrInt>(port),
  665. s, s ? Traits::length(s) : 0);
  666. }
  667. /**
  668. * @brief Synchronous send data
  669. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  670. * Note : If this function is called in communication thread, it will degenerates into async_send
  671. * and the return value is 0, you can use asio2::get_last_error() to check whether the
  672. * send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
  673. * means success, otherwise failed.
  674. * PodType (&data)[N] : double m[10]; send(m,5);
  675. */
  676. template<typename String, typename StrOrInt, class CharT, class SizeT>
  677. inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
  678. !std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, std::size_t>
  679. send(String&& host, StrOrInt&& port, CharT * s, SizeT count)
  680. {
  681. derived_t& derive = static_cast<derived_t&>(*this);
  682. return derive.send(std::forward<String>(host), std::forward<StrOrInt>(port),
  683. derive._data_persistence(s, count));
  684. }
  685. public:
  686. /**
  687. * @brief Synchronous send data,supporting multi data formats,
  688. * see asio::buffer(...) in /asio/buffer.hpp
  689. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  690. * Note : If this function is called in communication thread, it will degenerates into async_send
  691. * and the return value is 0, you can use asio2::get_last_error() to check whether the
  692. * send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
  693. * means success, otherwise failed.
  694. * use like this : std::string m; send(std::move(m)); can reducing memory allocation.
  695. * PodType * : send("abc");
  696. * PodType (&data)[N] : double m[10]; send(m);
  697. * std::array<PodType, N> : std::array<int,10> m; send(m);
  698. * std::vector<PodType, Allocator> : std::vector<float> m; send(m);
  699. * std::basic_string<Elem, Traits, Allocator> : std::string m; send(m);
  700. */
  701. template<class Endpoint, class DataT>
  702. inline typename std::enable_if_t<
  703. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, std::size_t>
  704. send(Endpoint&& endpoint, DataT&& data)
  705. {
  706. derived_t& derive = static_cast<derived_t&>(*this);
  707. std::future<std::pair<error_code, std::size_t>> future = derive.async_send(
  708. std::forward<Endpoint>(endpoint), std::forward<DataT>(data), asio::use_future);
  709. // Whether we run on the io_context thread
  710. if (derive.io_->running_in_this_thread())
  711. {
  712. std::future_status status = future.wait_for(std::chrono::nanoseconds(0));
  713. // async_send failed.
  714. if (status == std::future_status::ready)
  715. {
  716. set_last_error(future.get().first);
  717. return std::size_t(0);
  718. }
  719. // async_send success.
  720. else
  721. {
  722. set_last_error(asio::error::in_progress);
  723. return std::size_t(0);
  724. }
  725. }
  726. std::pair<error_code, std::size_t> pair = future.get();
  727. set_last_error(pair.first);
  728. return pair.second;
  729. }
  730. /**
  731. * @brief Synchronous send data
  732. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  733. * Note : If this function is called in communication thread, it will degenerates into async_send
  734. * and the return value is 0, you can use asio2::get_last_error() to check whether the
  735. * send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
  736. * means success, otherwise failed.
  737. * PodType * : send("abc");
  738. */
  739. template<class Endpoint, class CharT, class Traits = std::char_traits<CharT>>
  740. inline typename std::enable_if_t<
  741. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
  742. detail::is_char_v<CharT>, std::size_t>
  743. send(Endpoint&& endpoint, CharT * s)
  744. {
  745. derived_t& derive = static_cast<derived_t&>(*this);
  746. return derive.send(std::forward<Endpoint>(endpoint), s, s ? Traits::length(s) : 0);
  747. }
  748. /**
  749. * @brief Synchronous send data
  750. * You can call this function on the communication thread and anywhere,it's multi thread safed.
  751. * Note : If this function is called in communication thread, it will degenerates into async_send
  752. * and the return value is 0, you can use asio2::get_last_error() to check whether the
  753. * send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
  754. * means success, otherwise failed.
  755. * PodType (&data)[N] : double m[10]; send(m,5);
  756. */
  757. template<class Endpoint, class CharT, class SizeT>
  758. inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
  759. std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, std::size_t>
  760. send(Endpoint&& endpoint, CharT * s, SizeT count)
  761. {
  762. derived_t& derive = static_cast<derived_t&>(*this);
  763. return derive.send(std::forward<Endpoint>(endpoint), derive._data_persistence(s, count));
  764. }
  765. protected:
  766. template<typename String, typename StrOrInt, typename Data, typename Callback>
  767. inline void _do_resolve(String&& host, StrOrInt&& port, Data&& data, Callback&& callback)
  768. {
  769. derived_t& derive = static_cast<derived_t&>(*this);
  770. using resolver_type = asio::ip::udp::resolver;
  771. using endpoints_type = typename resolver_type::results_type;
  772. //using endpoints_iterator = typename endpoints_type::iterator;
  773. std::unique_ptr<resolver_type> resolver_ptr = std::make_unique<resolver_type>(
  774. derive.io_->context());
  775. // Before async_resolve execution is complete, we must hold the resolver object.
  776. // so we captured the resolver_ptr into the lambda callback function.
  777. resolver_type * rp = resolver_ptr.get();
  778. rp->async_resolve(std::forward<String>(host), detail::to_string(std::forward<StrOrInt>(port)),
  779. [&derive, p = derive.selfptr(), resolver_ptr = std::move(resolver_ptr),
  780. data = std::forward<Data>(data), callback = std::forward<Callback>(callback)]
  781. (const error_code& ec, const endpoints_type& endpoints) mutable
  782. {
  783. set_last_error(ec);
  784. if (ec)
  785. {
  786. callback(ec, 0);
  787. return;
  788. }
  789. decltype(endpoints.size()) i = 1;
  790. for (auto iter = endpoints.begin(); iter != endpoints.end(); ++iter, ++i)
  791. {
  792. derive.push_event(
  793. [&derive, id = derive.life_id(), endpoint = iter->endpoint(),
  794. p = (endpoints.size() == i ? std::move(p) : p),
  795. data = (endpoints.size() == i ? std::move(data) : data),
  796. callback = (endpoints.size() == i ? std::move(callback) : callback)]
  797. (event_queue_guard<derived_t> g) mutable
  798. {
  799. if (!derive.is_started())
  800. {
  801. set_last_error(asio::error::not_connected);
  802. callback(asio::error::not_connected, 0);
  803. return;
  804. }
  805. if (id != derive.life_id())
  806. {
  807. set_last_error(asio::error::operation_aborted);
  808. callback(asio::error::operation_aborted, 0);
  809. return;
  810. }
  811. clear_last_error();
  812. derive._do_send(endpoint, data, [g = std::move(g), f = std::move(callback)]
  813. (const error_code& ec, std::size_t bytes_sent) mutable
  814. {
  815. f(ec, bytes_sent);
  816. });
  817. });
  818. }
  819. });
  820. }
  821. };
  822. }
  823. #endif // !__ASIO2_UDP_SEND_COMPONENT_HPP__