WebSocketServer.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. using InABox.Core;
  2. using InABox.WebSocket.Shared;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Runtime.CompilerServices;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using WebSocketSharp;
  12. using WebSocketSharp.Server;
  13. using static InABox.Server.WebSocket.NotifyState;
  14. using InternalServer = WebSocketSharp.Server.WebSocketServer;
  15. using Logger = InABox.Core.Logger;
  16. namespace InABox.Server.WebSocket
  17. {
  18. public delegate void PollEvent(Session session);
  19. public class NotifyState
  20. {
  21. public class Session
  22. {
  23. public string ID { get; set; }
  24. public Guid SessionID { get; set; }
  25. public Platform Platform { get; set; }
  26. public Session(string id, Guid sessionID, Platform platform)
  27. {
  28. ID = id;
  29. SessionID = sessionID;
  30. Platform = platform;
  31. }
  32. }
  33. public ConcurrentDictionary<Guid, Session> SessionMap = new();
  34. public event PollEvent? OnPoll;
  35. public void Poll(Session session)
  36. {
  37. OnPoll?.Invoke(session);
  38. }
  39. }
  40. public class NotifyHandler : WebSocketBehavior
  41. {
  42. private NotifyState NotifyState;
  43. public NotifyHandler(NotifyState state)
  44. {
  45. NotifyState = state;
  46. }
  47. protected override void OnOpen()
  48. {
  49. Logger.Send(LogType.Information, "", $"WebSocket client connected");
  50. }
  51. protected override void OnClose(CloseEventArgs e)
  52. {
  53. Logger.Send(LogType.Information, "", $"WebSocket client disconnected");
  54. var sessionID = NotifyState.SessionMap.Where(x => x.Value.ID == ID).FirstOrDefault().Key;
  55. NotifyState.SessionMap.TryRemove(sessionID, out var session);
  56. }
  57. protected override void OnError(WebSocketSharp.ErrorEventArgs e)
  58. {
  59. Logger.Send(LogType.Error, "", $"WebSocket Error: {e.Message}");
  60. }
  61. private void DoInitial(InitialMessage initial)
  62. {
  63. var newSession = new Session(ID, initial.SessionID, initial.Platform);
  64. NotifyState.SessionMap[initial.SessionID] = newSession;
  65. NotifyState.Poll(newSession);
  66. }
  67. protected override void OnMessage(MessageEventArgs e)
  68. {
  69. Logger.Send(LogType.Information, "", "Message received");
  70. var message = SocketMessage.ReadMessage(e.RawData);
  71. if (message is InitialMessage initial)
  72. {
  73. DoInitial(initial);
  74. }
  75. }
  76. }
  77. public class WebSocketServer
  78. {
  79. private InternalServer Server;
  80. private NotifyState NotifyState = new();
  81. public event PollEvent? Poll;
  82. public int Port => Server.Port;
  83. public WebSocketServer(int port)
  84. {
  85. Server = new InternalServer(IPAddress.Any, port);
  86. Server.AddWebSocketService("/notify", NewNotify);
  87. NotifyState.OnPoll += NotifyState_Poll;
  88. }
  89. private void NotifyState_Poll(Session session)
  90. {
  91. Poll?.Invoke(session);
  92. }
  93. public NotifyHandler NewNotify()
  94. {
  95. return new NotifyHandler(NotifyState);
  96. }
  97. public IEnumerable<Guid> GetSessions(Platform platform)
  98. {
  99. return NotifyState.SessionMap.Where(x => x.Value.Platform == platform).Select(x => x.Key);
  100. }
  101. public void Push(Guid sessionID, SocketMessage message)
  102. {
  103. if(NotifyState.SessionMap.TryGetValue(sessionID, out var session))
  104. {
  105. using(var stream = new MemoryStream())
  106. {
  107. message.Write(stream);
  108. Server.WebSocketServices["/notify"].Sessions.SendToAsync(stream, (int)stream.Length, session.ID, (succ) => { });
  109. }
  110. }
  111. }
  112. private void PushMessage(SocketMessage message)
  113. {
  114. Server.WebSocketServices["/notify"].Sessions.Broadcast(message.WriteToBytes());
  115. }
  116. private void PushMessage(SocketMessage message, string session)
  117. {
  118. Server.WebSocketServices["/notify"].Sessions.SendTo(message.WriteToBytes(), session);
  119. }
  120. public void Push(Type TNotification, object notification)
  121. {
  122. PushMessage(NotifyMessage.Notify(TNotification, notification));
  123. }
  124. public void Push<TNotification>(TNotification notification)
  125. {
  126. PushMessage(NotifyMessage.Notify(notification));
  127. }
  128. public void Push(Guid sessionID, Type TNotification, object notification)
  129. {
  130. if(NotifyState.SessionMap.TryGetValue(sessionID, out var session))
  131. {
  132. PushMessage(NotifyMessage.Notify(TNotification, notification), session.ID);
  133. }
  134. }
  135. public void Push<TNotification>(Guid sessionID, TNotification notification)
  136. {
  137. if(NotifyState.SessionMap.TryGetValue(sessionID, out var session))
  138. {
  139. PushMessage(NotifyMessage.Notify(notification), session.ID);
  140. }
  141. }
  142. public void Start()
  143. {
  144. Server.Start();
  145. }
  146. public void Stop()
  147. {
  148. Server.Stop();
  149. }
  150. }
  151. }