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.

89 line
2.2KB

  1. public interface INetMqAccessor : IDisposable
  2. {
  3. void StartServer(string endpoint);
  4. void SendMessage(string message);
  5. event Action<string> OnMessageReceived;
  6. }
  7. public class NetMqAccessor : INetMqAccessor
  8. {
  9. private RouterSocket server;
  10. private NetMQPoller poller;
  11. public event Action<string> OnMessageReceived;
  12. public void StartServer(string endpoint)
  13. {
  14. server = new RouterSocket();
  15. server.Bind(endpoint);
  16. server.ReceiveReady += (s, e) =>
  17. {
  18. var msg = e.Socket.ReceiveMultipartMessage();
  19. var clientAddress = msg[0];
  20. var content = msg[2].ConvertToString();
  21. OnMessageReceived?.Invoke(content);
  22. var response = new NetMQMessage();
  23. response.Append(clientAddress);
  24. response.AppendEmptyFrame();
  25. response.Append($"Echo: {content}");
  26. server.SendMultipartMessage(response);
  27. };
  28. poller = new NetMQPoller { server };
  29. poller.RunAsync();
  30. }
  31. public void SendMessage(string message)
  32. {
  33. // Optionnel si tu veux aussi gérer un client ici
  34. }
  35. public void Dispose()
  36. {
  37. poller?.Stop();
  38. server?.Dispose();
  39. }
  40. }
  41. ////////
  42. public interface INetMqClientAccessor : IDisposable
  43. {
  44. void Connect(string endpoint);
  45. void SendMessage<T>(T message);
  46. Task<TResponse> SendAndReceive<TRequest, TResponse>(TRequest message);
  47. }
  48. public class NetMqClientAccessor : INetMqClientAccessor
  49. {
  50. private RequestSocket client;
  51. public void Connect(string endpoint)
  52. {
  53. client = new RequestSocket();
  54. client.Connect(endpoint);
  55. }
  56. public void SendMessage<T>(T message)
  57. {
  58. byte[] packed = MessagePackSerializer.Serialize(message);
  59. client.SendFrame(packed);
  60. }
  61. public async Task<TResponse> SendAndReceive<TRequest, TResponse>(TRequest message)
  62. {
  63. byte[] packed = MessagePackSerializer.Serialize(message);
  64. client.SendFrame(packed);
  65. // Attente de la réponse
  66. byte[] responseBytes = client.ReceiveFrameBytes();
  67. TResponse response = MessagePackSerializer.Deserialize<TResponse>(responseBytes);
  68. return response;
  69. }
  70. public void Dispose()
  71. {
  72. client?.Dispose();
  73. }
  74. }