ReceiveThreadSafeSocketExtensions.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace NetMQ
  9. {
  10. /// <summary>
  11. /// Receive methods for thread-safe sockets that support receiving
  12. /// </summary>
  13. public static class ReceiveThreadSafeSocketExtensions
  14. {
  15. #region Receiving byte array
  16. #region Blocking
  17. /// <summary>
  18. /// Receive a bytes from <paramref name="socket"/>, blocking until one arrives.
  19. /// </summary>
  20. /// <param name="socket">The socket to receive from.</param>
  21. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  22. /// <returns>The content of the received message.</returns>
  23. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  24. public static byte[] ReceiveBytes(this IThreadSafeInSocket socket,
  25. CancellationToken cancellationToken = default)
  26. {
  27. var msg = new Msg();
  28. msg.InitEmpty();
  29. try
  30. {
  31. socket.Receive(ref msg, cancellationToken);
  32. var data = msg.CloneData();
  33. return data;
  34. }
  35. finally
  36. {
  37. msg.Close();
  38. }
  39. }
  40. #endregion
  41. #region Immediate
  42. /// <summary>
  43. /// Attempt to receive a byte-array <paramref name="socket"/>.
  44. /// If no message is immediately available, return <c>false</c>.
  45. /// </summary>
  46. /// <param name="socket">The socket to receive from.</param>
  47. /// <param name="bytes">The content of the received message, or <c>null</c> if no message was available.</param>
  48. /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
  49. public static bool TryReceiveBytes(this IThreadSafeInSocket socket, [NotNullWhen(returnValue: true)] out byte[]? bytes)
  50. {
  51. return socket.TryReceiveBytes(TimeSpan.Zero, out bytes);
  52. }
  53. #endregion
  54. #region Timeout
  55. /// <summary>
  56. /// Attempt to receive a byte-array <paramref name="socket"/>.
  57. /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
  58. /// </summary>
  59. /// <param name="socket">The socket to receive from.</param>
  60. /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
  61. /// <param name="bytes">The content of the received message, or <c>null</c> if no message was available.</param>
  62. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  63. /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
  64. /// <remarks>The method would return false if cancellation has had requested.</remarks>
  65. public static bool TryReceiveBytes(this IThreadSafeInSocket socket, TimeSpan timeout,
  66. [NotNullWhen(returnValue: true)] out byte[]? bytes, CancellationToken cancellationToken = default)
  67. {
  68. var msg = new Msg();
  69. msg.InitEmpty();
  70. if (!socket.TryReceive(ref msg, timeout, cancellationToken))
  71. {
  72. msg.Close();
  73. bytes = null;
  74. return false;
  75. }
  76. bytes = msg.CloneData();
  77. msg.Close();
  78. return true;
  79. }
  80. #endregion
  81. #region Async
  82. /// <summary>
  83. /// Receive a bytes from <paramref name="socket"/> asynchronously.
  84. /// </summary>
  85. /// <param name="socket">The socket to receive from.</param>
  86. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  87. /// <returns>The content of the received message.</returns>
  88. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  89. public static ValueTask<byte[]> ReceiveBytesAsync(this IThreadSafeInSocket socket,
  90. CancellationToken cancellationToken = default)
  91. {
  92. if (TryReceiveBytes(socket, out var bytes))
  93. return new ValueTask<byte[]>(bytes);
  94. // TODO: this is a hack, eventually we need kind of IO ThreadPool for thread-safe socket to wait on asynchronously
  95. // and probably implement IValueTaskSource
  96. // TODO: should we avoid lambda here as it cause heap allocation for the environment?
  97. return new ValueTask<byte[]>(Task.Factory.StartNew(() => socket.ReceiveBytes(cancellationToken),
  98. cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default));
  99. }
  100. #endregion
  101. #region AsyncEnumerable
  102. #if NETSTANDARD2_1
  103. /// <summary>
  104. /// Provides a consuming IAsyncEnumerable for receiving messages from the socket.
  105. /// </summary>
  106. /// <param name="socket">The socket to receive from.</param>
  107. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  108. /// <returns>An IAsyncEnumerable that receive and returns messages from the socket.</returns>
  109. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  110. public static async IAsyncEnumerable<byte[]> ReceiveBytesAsyncEnumerable(
  111. this IThreadSafeInSocket socket,
  112. [EnumeratorCancellation] CancellationToken cancellationToken = default)
  113. {
  114. while (true)
  115. {
  116. yield return await socket.ReceiveBytesAsync(cancellationToken);
  117. }
  118. }
  119. #endif
  120. #endregion
  121. #endregion
  122. #region Receiving string
  123. #region Blocking
  124. /// <summary>
  125. /// Receive a string from <paramref name="socket"/>, blocking until one arrives, and decode using <see cref="SendReceiveConstants.DefaultEncoding"/>.
  126. /// </summary>
  127. /// <param name="socket">The socket to receive from.</param>
  128. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  129. /// <returns>The content of the received message.</returns>
  130. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  131. public static string ReceiveString(this IThreadSafeInSocket socket,
  132. CancellationToken cancellationToken = default)
  133. {
  134. return socket.ReceiveString(SendReceiveConstants.DefaultEncoding, cancellationToken);
  135. }
  136. /// <summary>
  137. /// Receive a string from <paramref name="socket"/>, blocking until one arrives, and decode using <paramref name="encoding"/>.
  138. /// </summary>
  139. /// <param name="socket">The socket to receive from.</param>
  140. /// <param name="encoding">The encoding used to convert the data to a string.</param>
  141. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  142. /// <returns>The content of the received message.</returns>
  143. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  144. public static string ReceiveString(this IThreadSafeInSocket socket, Encoding encoding,
  145. CancellationToken cancellationToken = default)
  146. {
  147. var msg = new Msg();
  148. msg.InitEmpty();
  149. try
  150. {
  151. socket.Receive(ref msg, cancellationToken);
  152. return msg.Size > 0
  153. ? msg.GetString(encoding)
  154. : string.Empty;
  155. }
  156. finally
  157. {
  158. msg.Close();
  159. }
  160. }
  161. #endregion
  162. #region Immediate
  163. /// <summary>
  164. /// Attempt to receive a string from <paramref name="socket"/>, and decode using <see cref="SendReceiveConstants.DefaultEncoding"/>.
  165. /// If no message is immediately available, return <c>false</c>.
  166. /// </summary>
  167. /// <param name="socket">The socket to receive from.</param>
  168. /// <param name="str">The content of the received message, or <c>null</c> if no message was available.</param>
  169. /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
  170. public static bool TryReceiveString(this IThreadSafeInSocket socket, [NotNullWhen(returnValue: true)] out string? str)
  171. {
  172. return socket.TryReceiveString(TimeSpan.Zero, SendReceiveConstants.DefaultEncoding, out str);
  173. }
  174. /// <summary>
  175. /// Attempt to receive a string from <paramref name="socket"/>, and decode using <paramref name="encoding"/>.
  176. /// If no message is immediately available, return <c>false</c>.
  177. /// </summary>
  178. /// <param name="socket">The socket to receive from.</param>
  179. /// <param name="encoding">The encoding used to convert the data to a string.</param>
  180. /// <param name="str">The content of the received message, or <c>null</c> if no message was available.</param>
  181. /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
  182. public static bool TryReceiveString(this IThreadSafeInSocket socket, Encoding encoding,
  183. [NotNullWhen(returnValue: true)] out string? str)
  184. {
  185. return socket.TryReceiveString(TimeSpan.Zero, encoding, out str);
  186. }
  187. #endregion
  188. #region Timeout
  189. /// <summary>
  190. /// Attempt to receive a string from <paramref name="socket"/>, and decode using <see cref="SendReceiveConstants.DefaultEncoding"/>.
  191. /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
  192. /// </summary>
  193. /// <param name="socket">The socket to receive from.</param>
  194. /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
  195. /// <param name="str">The conent of the received message, or <c>null</c> if no message was available.</param>
  196. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  197. /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
  198. /// <remarks>The method would return false if cancellation has had requested.</remarks>
  199. public static bool TryReceiveString(this IThreadSafeInSocket socket, TimeSpan timeout, [NotNullWhen(returnValue: true)] out string? str,
  200. CancellationToken cancellationToken = default)
  201. {
  202. return socket.TryReceiveString(timeout, SendReceiveConstants.DefaultEncoding, out str, cancellationToken);
  203. }
  204. /// <summary>
  205. /// Attempt to receive a string from <paramref name="socket"/>, and decode using <paramref name="encoding"/>.
  206. /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
  207. /// </summary>
  208. /// <param name="socket">The socket to receive from.</param>
  209. /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
  210. /// <param name="encoding">The encoding used to convert the data to a string.</param>
  211. /// <param name="str">The content of the received message, or <c>null</c> if no message was available.</param>
  212. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  213. /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
  214. /// <remarks>The method would return false if cancellation has had requested.</remarks>
  215. public static bool TryReceiveString(this IThreadSafeInSocket socket, TimeSpan timeout,
  216. Encoding encoding, [NotNullWhen(returnValue: true)] out string? str, CancellationToken cancellationToken = default)
  217. {
  218. var msg = new Msg();
  219. msg.InitEmpty();
  220. if (socket.TryReceive(ref msg, timeout, cancellationToken))
  221. {
  222. try
  223. {
  224. str = msg.Size > 0
  225. ? msg.GetString(encoding)
  226. : string.Empty;
  227. return true;
  228. }
  229. finally
  230. {
  231. msg.Close();
  232. }
  233. }
  234. str = null;
  235. msg.Close();
  236. return false;
  237. }
  238. #endregion
  239. #region Async
  240. /// <summary>
  241. /// Receive a string from <paramref name="socket"/> asynchronously.
  242. /// </summary>
  243. /// <param name="socket">The socket to receive from.</param>
  244. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  245. /// <returns>The content of the received message.</returns>
  246. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  247. public static ValueTask<string> ReceiveStringAsync(this IThreadSafeInSocket socket,
  248. CancellationToken cancellationToken = default)
  249. {
  250. if (TryReceiveString(socket, out var msg))
  251. return new ValueTask<string>(msg);
  252. // TODO: this is a hack, eventually we need kind of IO ThreadPool for thread-safe socket to wait on asynchronously
  253. // and probably implement IValueTaskSource
  254. return new ValueTask<string>(Task.Factory.StartNew(() => socket.ReceiveString(cancellationToken),
  255. cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default));
  256. }
  257. #endregion
  258. #region AsyncEnumerable
  259. #if NETSTANDARD2_1
  260. /// <summary>
  261. /// Provides a consuming IAsyncEnumerable for receiving messages from the socket.
  262. /// </summary>
  263. /// <param name="socket">The socket to receive from.</param>
  264. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  265. /// <returns>An IAsyncEnumerable that receive and returns messages from the socket.</returns>
  266. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  267. public static async IAsyncEnumerable<string> ReceiveStringAsyncEnumerable(
  268. this IThreadSafeInSocket socket,
  269. [EnumeratorCancellation] CancellationToken cancellationToken = default)
  270. {
  271. while (true)
  272. {
  273. yield return await socket.ReceiveStringAsync(cancellationToken);
  274. }
  275. }
  276. #endif
  277. #endregion
  278. #endregion
  279. }
  280. }