Communication.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using EventBus;
  2. using ICommunication;
  3. using System.Runtime.Serialization;
  4. namespace LocalCommunication
  5. {
  6. [CommunicationType(true)]
  7. public class Communication : ICommunication.ICommunication
  8. {
  9. public string IP => eventBus == null ? "" : eventBus.IP;
  10. public int Port => eventBus == null ? 0 : eventBus.Port;
  11. public bool IsLan { get; } = true;
  12. public bool IsConnected => eventBus == null ? false : eventBus.IsConnected;
  13. private TcpEventBus.TcpEventBus eventBus;
  14. public bool IsService { get; private set; }
  15. public event EventHandler Connected;
  16. public event EventHandler Disconnected;
  17. public void Close()
  18. {
  19. eventBus?.Close();
  20. }
  21. public void Connect(string ip, int port)
  22. {
  23. IsService = false;
  24. eventBus = TcpEventBus.TcpEventBus.CreateClient(ip, port, 5000);
  25. eventBus.Connected += (_, _) => this.Connected?.Invoke(this, EventArgs.Empty);
  26. eventBus.Disconnected += (_, _) => this.Disconnected?.Invoke(this, EventArgs.Empty);
  27. }
  28. public IEventData<TData>? GetEvent<TData>()
  29. {
  30. return eventBus?.GetEvent<TData>();
  31. }
  32. public IEventData<TData, T>? GetEvent<TData, T>()
  33. {
  34. return eventBus?.GetEvent<TData, T>();
  35. }
  36. public IAnonymousEventData? GetEvent(string eventName)
  37. {
  38. return eventBus?.GetEvent(eventName);
  39. }
  40. public IAnonymousEventData<T>? GetEvent<T>(string eventName)
  41. {
  42. return eventBus?.GetEvent<T>(eventName);
  43. }
  44. public void Start()
  45. {
  46. eventBus?.Start();
  47. }
  48. public void StartService(string ip,int port)
  49. {
  50. IsService = true;
  51. eventBus = TcpEventBus.TcpEventBus.CreateService(ip,port, 5000);
  52. eventBus.Connected += (_, _) => this.Connected?.Invoke(this, EventArgs.Empty);
  53. eventBus.Disconnected += (_, _) => this.Disconnected?.Invoke(this, EventArgs.Empty);
  54. }
  55. }
  56. }