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. lock (thisHub.Connection.SyncRoot)
  130. {
  131. // Start over the counter if we are reached the max value if the UInt64 type.
  132. // 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 deuggability.
  133. thisHub.Connection.ClientMessageCounter %= UInt64.MaxValue;
  134. // Create and send the client message
  135. return thisHub.Call(new ClientMessage(this, method, args, thisHub.Connection.ClientMessageCounter++, onResult, onResultError, onProgress));
  136. }
  137. }
  138. #endregion
  139. #region IHub Implementation
  140. bool IHub.Call(ClientMessage msg)
  141. {
  142. IHub thisHub = this as IHub;
  143. lock (thisHub.Connection.SyncRoot)
  144. {
  145. if (!thisHub.Connection.SendJson(BuildMessage(msg)))
  146. return false;
  147. SentMessages.Add(msg.CallIdx, msg);
  148. }
  149. return true;
  150. }
  151. /// <summary>
  152. /// Return true if this hub sent the message with the given id.
  153. /// </summary>
  154. bool IHub.HasSentMessageId(UInt64 id)
  155. {
  156. return SentMessages.ContainsKey(id);
  157. }
  158. /// <summary>
  159. /// Called on the manager's close.
  160. /// </summary>
  161. void IHub.Close()
  162. {
  163. SentMessages.Clear();
  164. }
  165. /// <summary>
  166. /// Called when the client receives an order to call a hub-function.
  167. /// </summary>
  168. void IHub.OnMethod(MethodCallMessage msg)
  169. {
  170. // Merge the newly received states with the old one
  171. MergeState(msg.State);
  172. if (OnMethodCall != null)
  173. {
  174. try
  175. {
  176. OnMethodCall(this, msg.Method, msg.Arguments);
  177. }
  178. catch(Exception ex)
  179. {
  180. HTTPManager.Logger.Exception("Hub - " + this.Name, "IHub.OnMethod - OnMethodCall", ex);
  181. }
  182. }
  183. OnMethodCallCallbackDelegate callback;
  184. if (MethodTable.TryGetValue(msg.Method, out callback) && callback != null)
  185. {
  186. try
  187. {
  188. callback(this, msg);
  189. }
  190. catch(Exception ex)
  191. {
  192. HTTPManager.Logger.Exception("Hub - " + this.Name, "IHub.OnMethod - callback", ex);
  193. }
  194. }
  195. else
  196. HTTPManager.Logger.Warning("Hub - " + this.Name, string.Format("[Client] {0}.{1} (args: {2})", this.Name, msg.Method, msg.Arguments.Length));
  197. }
  198. /// <summary>
  199. /// Called when the client receives back messages as a result of a server method call.
  200. /// </summary>
  201. void IHub.OnMessage(IServerMessage msg)
  202. {
  203. ClientMessage originalMsg;
  204. UInt64 id = (msg as IHubMessage).InvocationId;
  205. if (!SentMessages.TryGetValue(id, out originalMsg))
  206. {
  207. // This can happen when a result message removes the ClientMessage from the SentMessages dictionary,
  208. // then a late come progress message tries to access it
  209. HTTPManager.Logger.Warning("Hub - " + this.Name, "OnMessage - Sent message not found with id: " + id.ToString());
  210. return;
  211. }
  212. switch(msg.Type)
  213. {
  214. case MessageTypes.Result:
  215. ResultMessage result = msg as ResultMessage;
  216. // Merge the incoming State before firing the events
  217. MergeState(result.State);
  218. if (originalMsg.ResultCallback != null)
  219. {
  220. try
  221. {
  222. originalMsg.ResultCallback(this, originalMsg, result);
  223. }
  224. catch(Exception ex)
  225. {
  226. HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultCallback", ex);
  227. }
  228. }
  229. SentMessages.Remove(id);
  230. break;
  231. case MessageTypes.Failure:
  232. FailureMessage error = msg as FailureMessage;
  233. // Merge the incoming State before firing the events
  234. MergeState(error.State);
  235. if (originalMsg.ResultErrorCallback != null)
  236. {
  237. try
  238. {
  239. originalMsg.ResultErrorCallback(this, originalMsg, error);
  240. }
  241. catch(Exception ex)
  242. {
  243. HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultErrorCallback", ex);
  244. }
  245. }
  246. SentMessages.Remove(id);
  247. break;
  248. case MessageTypes.Progress:
  249. if (originalMsg.ProgressCallback != null)
  250. {
  251. try
  252. {
  253. originalMsg.ProgressCallback(this, originalMsg, msg as ProgressMessage);
  254. }
  255. catch(Exception ex)
  256. {
  257. HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ProgressCallback", ex);
  258. }
  259. }
  260. break;
  261. }
  262. }
  263. #endregion
  264. #region Helper Functions
  265. /// <summary>
  266. /// Merges the current and the new states.
  267. /// </summary>
  268. #if BESTHTTP_SIGNALR_WITH_JSONDOTNET
  269. private void MergeState(IDictionary<string, Newtonsoft.Json.Linq.JToken> state)
  270. #else
  271. private void MergeState(IDictionary<string, object> state)
  272. #endif
  273. {
  274. if (state != null && state.Count > 0)
  275. foreach (var kvp in state)
  276. this.State[kvp.Key] = kvp.Value;
  277. }
  278. /// <summary>
  279. /// Builds a JSon string from the given message.
  280. /// </summary>
  281. private string BuildMessage(ClientMessage msg)
  282. {
  283. try
  284. {
  285. builder.Append("{\"H\":\"");
  286. builder.Append(this.Name);
  287. builder.Append("\",\"M\":\"");
  288. builder.Append(msg.Method);
  289. builder.Append("\",\"A\":");
  290. string jsonEncoded = string.Empty;
  291. // Arguments
  292. if (msg.Args != null && msg.Args.Length > 0)
  293. jsonEncoded = (this as IHub).Connection.JsonEncoder.Encode(msg.Args);
  294. else
  295. jsonEncoded = "[]";
  296. builder.Append(jsonEncoded);
  297. builder.Append(",\"I\":\"");
  298. builder.Append(msg.CallIdx.ToString());
  299. builder.Append("\"");
  300. // State, if any
  301. if (msg.Hub.state != null && msg.Hub.state.Count > 0)
  302. {
  303. builder.Append(",\"S\":");
  304. jsonEncoded = (this as IHub).Connection.JsonEncoder.Encode(msg.Hub.state);
  305. builder.Append(jsonEncoded);
  306. }
  307. builder.Append("}");
  308. return builder.ToString();
  309. }
  310. catch (Exception ex)
  311. {
  312. HTTPManager.Logger.Exception("Hub - " + this.Name, "Send", ex);
  313. return null;
  314. }
  315. finally
  316. {
  317. // reset the StringBuilder instance, to reuse next time
  318. builder.Length = 0;
  319. }
  320. }
  321. #endregion
  322. }
  323. }
  324. #endif