PairSocket.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Threading;
  3. using NetMQ.Core;
  4. namespace NetMQ.Sockets
  5. {
  6. /// <summary>
  7. /// A PairSocket is a NetMQSocket, usually used to synchronize two threads - using only one socket on each side.
  8. /// </summary>
  9. public class PairSocket : NetMQSocket
  10. {
  11. private static int s_sequence;
  12. /// <summary>
  13. /// Create a new PairSocket and attach socket to zero or more endpoints.
  14. /// </summary>
  15. /// <param name="connectionString">List of NetMQ endpoints, separated by commas and prefixed by '@' (to bind the socket) or '>' (to connect the socket).
  16. /// Default action is connect (if endpoint doesn't start with '@' or '>')</param>
  17. /// <example><code>var socket = new PairSocket(">tcp://127.0.0.1:5555,@tcp://127.0.0.1:55556");</code></example>
  18. public PairSocket(string? connectionString = null) : base(ZmqSocketType.Pair, connectionString, DefaultAction.Connect)
  19. {
  20. }
  21. /// <summary>
  22. /// Create a new PairSocket based upon the given SocketBase.
  23. /// </summary>
  24. /// <param name="socketHandle">the SocketBase to create the new socket from</param>
  25. internal PairSocket(SocketBase socketHandle)
  26. : base(socketHandle)
  27. {
  28. }
  29. /// <summary>
  30. /// Create and return an inproc pipe where socket1 is bound and socket2 is connected.
  31. /// </summary>
  32. /// <param name="socket1">the Bind socket</param>
  33. /// <param name="socket2">the Connect socket</param>
  34. public static void CreateSocketPair(out PairSocket socket1, out PairSocket socket2)
  35. {
  36. string address = $"inproc://NetMQSocketPair#{Interlocked.Increment(ref s_sequence)}";
  37. socket1 = new PairSocket();
  38. socket1.Bind(address);
  39. socket2 = new PairSocket();
  40. socket2.Connect(address);
  41. }
  42. /// <summary>
  43. /// Create and return an inproc pipe where socket1 is bound and socket2 is connected.
  44. /// </summary>
  45. /// <param name="socket1">the Bind socket</param>
  46. /// <param name="socket2">the Connect socket</param>
  47. /// <param name="initSocket1">Method to initialize socket1 before connection</param>
  48. /// <param name="initSocket2">Method to initialize socket2 before connection</param>
  49. public static void CreateSocketPair(out PairSocket socket1, out PairSocket socket2, Action<PairSocket> initSocket1, Action<PairSocket> initSocket2)
  50. {
  51. string address = $"inproc://NetMQSocketPair#{Interlocked.Increment(ref s_sequence)}";
  52. socket1 = new PairSocket();
  53. initSocket1(socket1);
  54. socket1.Bind(address);
  55. socket2 = new PairSocket();
  56. initSocket2(socket2);
  57. socket2.Connect(address);
  58. }
  59. }
  60. }