Hub.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #if !BESTHTTP_DISABLE_SIGNALR
  2. using System;
  3. using System.Collections.Generic;
  4. using BestHTTP.SignalR.Messages;
  5. using System.Text;
  6. namespace BestHTTP.SignalR.Hubs
  7. {
  8. public delegate void OnMethodCallDelegate(Hub hub, string method, params object[] args);
  9. public delegate void OnMethodCallCallbackDelegate(Hub hub, MethodCallMessage methodCall);
  10. public delegate void OnMethodResultDelegate(Hub hub, ClientMessage originalMessage, ResultMessage result);
  11. public delegate void OnMethodFailedDelegate(Hub hub, ClientMessage originalMessage, FailureMessage error);
  12. public delegate void OnMethodProgressDelegate(Hub hub, ClientMessage originialMessage, ProgressMessage progress);
  13. /// <summary>
  14. /// Represents a clientside Hub. This class can be used as a base class to encapsulate proxy functionalities.
  15. /// </summary>
  16. public class Hub : IHub
  17. {
  18. #region Public Properties
  19. /// <summary>
  20. /// Name of this hub.
  21. /// </summary>
  22. public string Name { get; private set; }
  23. /// <summary>
  24. /// Server and user set state of the hub.
  25. /// </summary>
  26. public Dictionary<string, object> State
  27. {
  28. // Create only when we need to.
  29. get
  30. {
  31. if (state == null)
  32. state = new Dictionary<string, object>();
  33. return state;
  34. }
  35. }
  36. private Dictionary<string, object> state;
  37. /// <summary>
  38. /// Event called every time when the server sends an order to call a method on the client.
  39. /// </summary>
  40. public event OnMethodCallDelegate OnMethodCall;
  41. #endregion
  42. #region Privates
  43. /// <summary>
  44. /// Table of the sent messages. These messages will be removed from this table when a Result message is received from the server.
  45. /// </summary>
  46. private Dictionary<UInt64, ClientMessage> SentMessages = new Dictionary<ulong, ClientMessage>();
  47. /// <summary>
  48. /// Methodname -> callback delegate mapping. This table stores the server callable functions.
  49. /// </summary>
  50. private Dictionary<string, OnMethodCallCallbackDelegate> MethodTable = new Dictionary<string, OnMethodCallCallbackDelegate>();
  51. /// <summary>
  52. /// A reusable StringBuilder to save some GC allocs
  53. /// </summary>
  54. private StringBuilder builder = new StringBuilder();
  55. #endregion
  56. Connection IHub.Connection { get; set; }
  57. public Hub(string name)
  58. :this(name, null)
  59. {
  60. }
  61. public Hub(string name, Connection manager)
  62. {
  63. this.Name = name;
  64. (this as IHub).Connection = manager;
  65. }
  66. #region Public Hub Functions
  67. /// <summary>
  68. /// Registers a callback function to the given method.
  69. /// </summary>
  70. public void On(string method, OnMethodCallCallbackDelegate callback)
  71. {
  72. MethodTable[method] = callback;
  73. }
  74. /// <summary>
  75. /// Removes callback from the given method.
  76. /// </summary>
  77. /// <param name="method"></param>
  78. public void Off(string method)
  79. {
  80. MethodTable[method] = null;
  81. }
  82. /// <summary>
  83. /// Orders the server to call a method with the given arguments.
  84. /// </summary>
  85. /// <returns>True if the plugin was able to send out the message</returns>
  86. public bool Call(string method, params object[] args)
  87. {
  88. return Call(method, null, null, null, args);
  89. }
  90. /// <summary>
  91. /// Orders the server to call a method with the given arguments.
  92. /// The onResult callback will be called when the server successfully called the function.
  93. /// </summary>
  94. /// <returns>True if the plugin was able to send out the message</returns>
  95. public bool Call(string method, OnMethodResultDelegate onResult, params object[] args)
  96. {
  97. return Call(method, onResult, null, null, args);
  98. }
  99. /// <summary>
  100. /// Orders the server to call a method with the given arguments.
  101. /// The onResult callback will be called when the server successfully called the function.
  102. /// The onResultError will be called when the server can't call the function, or when the function throws an exception.
  103. /// </summary>
  104. /// <returns>True if the plugin was able to send out the message</returns>
  105. public bool Call(string method, OnMethodResultDelegate onResult, OnMethodFailedDelegate onResultError, params object[] args)
  106. {
  107. return Call(method, onResult, onResultError, null, args);
  108. }
  109. /// <summary>
  110. /// Orders the server to call a method with the given arguments.
  111. /// The onResult callback will be called when the server successfully called the function.
  112. /// The onProgress callback called multiple times when the method is a long running function and reports back its progress.
  113. /// </summary>
  114. /// <returns>True if the plugin was able to send out the message</returns>
  115. public bool Call(string method, OnMethodResultDelegate onResult, OnMethodProgressDelegate onProgress, params object[] args)
  116. {
  117. return Call(method, onResult, null, onProgress, args);
  118. }
  119. /// <summary>
  120. /// Orders the server to call a method with the given arguments.
  121. /// The onResult callback will be called when the server successfully called the function.
  122. /// The onResultError will be called when the server can't call the function, or when the function throws an exception.
  123. /// The onProgress callback called multiple times when the method is a long running function and reports back its progress.
  124. /// </summary>
  125. /// <returns>True if the plugin was able to send out the message</returns>
  126. public bool Call(string method, OnMethodResultDelegate onResult, OnMethodFailedDelegate onResultError, OnMethodProgressDelegate onProgress, params object[] args)
  127. {
  128. IHub thisHub = this as IHub;
  129. // Start over the counter if we are reached the max value if the long type.
  130. // While we are using this property only here, we don't want to make it static to avoid another thread synchronization, neither we want to make it a Hub-instance field to achieve better debuggability.
  131. long newValue, originalValue;
  132. do
  133. {
  134. originalValue = thisHub.Connection.ClientMessageCounter;
  135. newValue = (originalValue % long.MaxValue) + 1;
  136. } while (System.Threading.Interlocked.CompareExchange(ref thisHub.Connection.ClientMessageCounter, newValue, originalValue) != originalValue);
  137. // Create and send the client message
  138. return thisHub.Call(new ClientMessage(this, method, args, (ulong)thisHub.Connection.ClientMessageCounter, onResult, onResultError, onProgress));
  139. }
  140. #endregion
  141. #region IHub Implementation
  142. bool IHub.Call(ClientMessage msg)
  143. {
  144. IHub thisHub = this as IHub;
  145. if (!thisHub.Connection.SendJson(BuildMessage(msg)))
  146. return false;
  147. SentMessages.Add(msg.CallIdx, msg);
  148. return true;
  149. }
  150. /// <summary>
  151. /// Return true if this hub sent the message with the given id.
  152. /// </summary>
  153. bool IHub.HasSentMessageId(UInt64 id)
  154. {
  155. return SentMessages.ContainsKey(id);
  156. }
  157. /// <summary>
  158. /// Called on the manager's close.
  159. /// </summary>
  160. void IHub.Close()
  161. {
  162. SentMessages.Clear();
  163. }
  164. /// <summary>
  165. /// Called when the client receives an order to call a hub-function.
  166. /// </summary>
  167. void IHub.OnMethod(MethodCallMessage msg)
  168. {
  169. // Merge the newly received states with the old one
  170. MergeState(msg.State);
  171. if (OnMethodCall != null)
  172. {
  173. try
  174. {
  175. OnMethodCall(this, msg.Method, msg.Arguments);
  176. }
  177. catch(Exception ex)
  178. {
  179. HTTPManager.Logger.Exception("Hub - " + this.Name, "IHub.OnMethod - OnMethodCall", ex);
  180. }
  181. }
  182. OnMethodCallCallbackDelegate callback;
  183. if (MethodTable.TryGetValue(msg.Method, out callback) && callback != null)
  184. {
  185. try
  186. {
  187. callback(this, msg);
  188. }
  189. catch(Exception ex)
  190. {
  191. HTTPManager.Logger.Exception("Hub - " + this.Name, "IHub.OnMethod - callback", ex);
  192. }
  193. }
  194. else if (OnMethodCall == null)
  195. HTTPManager.Logger.Warning("Hub - " + this.Name, string.Format("[Client] {0}.{1} (args: {2})", this.Name, msg.Method, msg.Arguments.Length));
  196. }
  197. /// <summary>
  198. /// Called when the client receives back messages as a result of a server method call.
  199. /// </summary>
  200. void IHub.OnMessage(IServerMessage msg)
  201. {
  202. ClientMessage originalMsg;
  203. UInt64 id = (msg as IHubMessage).InvocationId;
  204. if (!SentMessages.TryGetValue(id, out originalMsg))
  205. {
  206. // This can happen when a result message removes the ClientMessage from the SentMessages dictionary,
  207. // then a late come progress message tries to access it
  208. HTTPManager.Logger.Warning("Hub - " + this.Name, "OnMessage - Sent message not found with id: " + id.ToString());
  209. return;
  210. }
  211. switch(msg.Type)
  212. {
  213. case MessageTypes.Result:
  214. ResultMessage result = msg as ResultMessage;
  215. // Merge the incoming State before firing the events
  216. MergeState(result.State);
  217. if (originalMsg.ResultCallback != null)
  218. {
  219. try
  220. {
  221. originalMsg.ResultCallback(this, originalMsg, result);
  222. }
  223. catch(Exception ex)
  224. {
  225. HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultCallback", ex);
  226. }
  227. }
  228. SentMessages.Remove(id);
  229. break;
  230. case MessageTypes.Failure:
  231. FailureMessage error = msg as FailureMessage;
  232. // Merge the incoming State before firing the events
  233. MergeState(error.State);
  234. if (originalMsg.ResultErrorCallback != null)
  235. {
  236. try
  237. {
  238. originalMsg.ResultErrorCallback(this, originalMsg, error);
  239. }
  240. catch(Exception ex)
  241. {
  242. HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultErrorCallback", ex);
  243. }
  244. }
  245. SentMessages.Remove(id);
  246. break;
  247. case MessageTypes.Progress:
  248. if (originalMsg.ProgressCallback != null)
  249. {
  250. try
  251. {
  252. originalMsg.ProgressCallback(this, originalMsg, msg as ProgressMessage);
  253. }
  254. catch(Exception ex)
  255. {
  256. HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ProgressCallback", ex);
  257. }
  258. }
  259. break;
  260. }
  261. }
  262. #endregion
  263. #region Helper Functions
  264. /// <summary>
  265. /// Merges the current and the new states.
  266. /// </summary>
  267. #if BESTHTTP_SIGNALR_WITH_JSONDOTNET
  268. private void MergeState(IDictionary<string, Newtonsoft.Json.Linq.JToken> state)
  269. #else
  270. private void MergeState(IDictionary<string, object> state)
  271. #endif
  272. {
  273. if (state != null && state.Count > 0)
  274. foreach (var kvp in state)
  275. this.State[kvp.Key] = kvp.Value;
  276. }
  277. /// <summary>
  278. /// Builds a JSon string from the given message.
  279. /// </summary>
  280. private string BuildMessage(ClientMessage msg)
  281. {
  282. try
  283. {
  284. builder.Append("{\"H\":\"");
  285. builder.Append(this.Name);
  286. builder.Append("\",\"M\":\"");
  287. builder.Append(msg.Method);
  288. builder.Append("\",\"A\":");
  289. string jsonEncoded = string.Empty;
  290. // Arguments
  291. if (msg.Args != null && msg.Args.Length > 0)
  292. jsonEncoded = (this as IHub).Connection.JsonEncoder.Encode(msg.Args);
  293. else
  294. jsonEncoded = "[]";
  295. builder.Append(jsonEncoded);
  296. builder.Append(",\"I\":\"");
  297. builder.Append(msg.CallIdx.ToString());
  298. builder.Append("\"");
  299. // State, if any
  300. if (msg.Hub.state != null && msg.Hub.state.Count > 0)
  301. {
  302. builder.Append(",\"S\":");
  303. jsonEncoded = (this as IHub).Connection.JsonEncoder.Encode(msg.Hub.state);
  304. builder.Append(jsonEncoded);
  305. }
  306. builder.Append("}");
  307. return builder.ToString();
  308. }
  309. catch (Exception ex)
  310. {
  311. HTTPManager.Logger.Exception("Hub - " + this.Name, "Send", ex);
  312. return null;
  313. }
  314. finally
  315. {
  316. // reset the StringBuilder instance, to reuse next time
  317. builder.Length = 0;
  318. }
  319. }
  320. #endregion
  321. }
  322. }
  323. #endif