RTCommunicator_SingalR.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using Microsoft.AspNetCore.SignalR.Client;
  2. using RTCommunicatorBase;
  3. using System.Threading.Tasks;
  4. namespace RTCommunicatorSingalR;
  5. public class RTCommunicator_SingalR : IRTMini8Sender
  6. {
  7. private HubConnection _hubConnection;
  8. private IRTMini8Provider _provider;
  9. private string _ipAddress;
  10. private int _port;
  11. bool IRTMini8Sender.Initialize(IRTMini8Provider provider)
  12. {
  13. if (provider is null)
  14. return false;
  15. if (this._provider is not null)
  16. return false;
  17. this._provider = provider;
  18. return true;
  19. }
  20. bool IRTMini8Sender.StartService(string ip, int port)
  21. {
  22. if (_provider is null)
  23. return false;
  24. if (this._hubConnection is not null)
  25. return false;
  26. if (string.IsNullOrEmpty(ip) || port < 5000 || port > ushort.MaxValue)
  27. return false;
  28. HubConnection tempHub = new HubConnectionBuilder().WithUrl($"http://{ip}:{port}/RTHub").WithAutomaticReconnect().Build();
  29. this._ipAddress = ip;
  30. this._port = port;
  31. //注册断线及重连事件
  32. tempHub.Closed += Hub_Closed; ;
  33. tempHub.Reconnected += Hub_Reconnected;
  34. tempHub.Reconnecting += Hub_Reconnecting;
  35. try
  36. {
  37. tempHub.StartAsync().Wait();
  38. this._provider?.Connected(this._ipAddress, this._port);
  39. }
  40. catch
  41. {
  42. return false;
  43. }
  44. this._hubConnection = tempHub;
  45. return true;
  46. }
  47. bool IRTMini8Sender.SelectConfigFile(string name)
  48. {
  49. try
  50. {
  51. return this._hubConnection.InvokeAsync<bool>("SelectConfigFile", name).Result;
  52. }
  53. catch
  54. {
  55. return false;
  56. }
  57. }
  58. bool IRTMini8Sender.CloseService()
  59. {
  60. this._hubConnection?.DisposeAsync();
  61. this._hubConnection = null;
  62. this._provider = null;
  63. return true;
  64. }
  65. private Task Hub_Reconnecting(System.Exception arg)
  66. {
  67. this._provider?.DisConnected(this._ipAddress, this._port);
  68. return Task.CompletedTask;
  69. }
  70. private Task Hub_Reconnected(string arg)
  71. {
  72. this._provider?.Connected(this._ipAddress, this._port);
  73. return Task.CompletedTask;
  74. }
  75. private Task Hub_Closed(System.Exception arg)
  76. {
  77. this._provider?.DisConnected(this._ipAddress, this._port);
  78. return Task.CompletedTask;
  79. }
  80. }