JCEngine.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using BestHTTP.WebSocket;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Linq;
  7. using JC.Unity;
  8. using UnityEngine;
  9. namespace JCEngineCore {
  10. public class JCEngine {
  11. private static string url;
  12. public static void boot(string url, JCEntity entity) {
  13. JCEngine.url = url;
  14. new JCEngineCore.WebSocketServer(url, entity);
  15. }
  16. public static void reboot(JCEntity entity) {
  17. new JCEngineCore.WebSocketServer(url, entity);
  18. }
  19. public static void bootNew(string url, JCEntity entity) {
  20. new JCEngineCore.WebSocketServer(url, entity);
  21. }
  22. }
  23. public class JCEntity {
  24. public int id;
  25. public JCEngineCore.Channel channel;
  26. public bool isValid;
  27. public bool loaded;
  28. public Dictionary<string, object> components = new Dictionary<string, object>();
  29. public virtual void onLoad() {}
  30. public virtual void onReload() {}
  31. public virtual void onDestroy() {}
  32. public virtual void onMiss() {}
  33. public bool call(string func, params object[] args) {
  34. return call(func, args, null);
  35. }
  36. public bool call(string func, object[] args = null, Delegate callback = null) {
  37. if (this.isValid) {
  38. string uuid = "";
  39. int type = Convert.ToInt32(JCEngineCore.DataType.FUNCTION);
  40. if (func.IndexOf(".") > -1) {
  41. type = Convert.ToInt32(JCEngineCore.DataType.METHOD);
  42. uuid = JCEngineCore.CallbackHandler.addCallback(callback);
  43. }
  44. if (args == null) {
  45. args = new object[]{};
  46. }
  47. JCEngineCore.Data data = new JCEngineCore.Data();
  48. data.uuid = uuid;
  49. data.type = type;
  50. data.func = func;
  51. data.args = args;
  52. this.channel.writeAndFlush(JsonConvert.SerializeObject(data));
  53. return true;
  54. }
  55. return false;
  56. }
  57. }
  58. public class Channel {
  59. private WebSocket webSocket;
  60. public Channel (WebSocket webSocket) {
  61. this.webSocket = webSocket;
  62. }
  63. public void writeAndFlush(string text) {
  64. this.webSocket.Send(text);
  65. }
  66. public void close() {
  67. this.webSocket.Close();
  68. }
  69. }
  70. class WebSocketServer {
  71. private WebSocket webSocket;
  72. private JCEntity tempEntity;
  73. private Coroutine heartBeatCoroutine;
  74. public WebSocketServer(string url, JCEntity entity) {
  75. this.webSocket = new WebSocket(new Uri(url));
  76. this.webSocket.StartPingThread = true;
  77. this.tempEntity = entity;
  78. this.webSocket.OnOpen += delegate(WebSocket webSocket) {
  79. this.call("loadTempEntity");
  80. };
  81. this.webSocket.OnClosed += delegate(WebSocket webSocket, UInt16 code, string message) {
  82. this.destroyTempEntity();
  83. };
  84. this.webSocket.OnError += delegate(WebSocket webSocket, Exception ex) {
  85. this.destroyTempEntity();
  86. };
  87. this.webSocket.OnMessage += delegate(WebSocket webSocket, string message) {
  88. this.invoke(JsonConvert.DeserializeObject<Data>(message));
  89. };
  90. this.webSocket.Open();
  91. }
  92. private void call(string func, object[] args = null) {
  93. if (args == null) {
  94. args = new object[]{};
  95. }
  96. Data data = new Data();
  97. data.uuid = "";
  98. data.type = Convert.ToInt32(DataType.EVENT);
  99. data.func = func;
  100. data.args = args;
  101. this.webSocket.Send(JsonConvert.SerializeObject(data));
  102. }
  103. private void invoke(Data data) {
  104. DataType dataType = (DataType) data.type;
  105. if (dataType == DataType.EVENT) {
  106. System.Reflection.MethodInfo method = this.GetType().GetMethod(data.func);
  107. Utility.FormatArgsType(data.args, method.GetParameters());
  108. method.Invoke(this, data.args);
  109. return;
  110. }
  111. if (dataType == DataType.FUNCTION) {
  112. if (this.tempEntity.isValid) {
  113. string func = data.func;
  114. object context = this.tempEntity;;
  115. int pointIndex = func.LastIndexOf(".");
  116. if (pointIndex > -1) {
  117. context = null;
  118. string key = func.Substring(0, pointIndex);
  119. object matchContext;
  120. this.tempEntity.components.TryGetValue(key, out matchContext);
  121. if (matchContext != null) {
  122. func = func.Substring(pointIndex + 1);
  123. context = matchContext;
  124. }
  125. }
  126. if (context != null) {
  127. System.Reflection.MethodInfo method = context.GetType().GetMethod(func);
  128. Utility.FormatArgsType(data.args, method.GetParameters());
  129. method.Invoke(context, data.args);
  130. }
  131. }
  132. return;
  133. }
  134. if (dataType == DataType.METHOD) {
  135. CallbackHandler.handleCallback(data);
  136. }
  137. }
  138. public void loadTempEntity(int id) {
  139. this.tempEntity.id = id;
  140. this.tempEntity.channel = new Channel(this.webSocket);
  141. this.tempEntity.isValid = true;
  142. try {
  143. if (this.tempEntity.loaded) {
  144. this.tempEntity.onReload();
  145. } else {
  146. this.tempEntity.onLoad();
  147. }
  148. } catch (Exception) {}
  149. this.tempEntity.loaded = true;
  150. if (heartBeatCoroutine == null) {
  151. heartBeatCoroutine = CoroutineStarter.Start(doHeartBeat());
  152. }
  153. }
  154. public void destroyTempEntity() {
  155. if (heartBeatCoroutine != null) {
  156. CoroutineStarter.Stop(heartBeatCoroutine);
  157. heartBeatCoroutine = null;
  158. }
  159. if (this.tempEntity.isValid) {
  160. this.tempEntity.isValid = false;
  161. this.tempEntity.onDestroy();
  162. } else {
  163. this.tempEntity.onMiss();
  164. }
  165. }
  166. IEnumerator doHeartBeat() {
  167. while (true) {
  168. try {
  169. call("doHeartBeat");
  170. } catch (System.Exception) {}
  171. yield return new WaitForSecondsRealtime(5f);
  172. }
  173. }
  174. }
  175. class CallbackHandler {
  176. private static int nextID = 0;
  177. private static Dictionary<string, CallbackInfo> mapper = new Dictionary<string, CallbackInfo>();
  178. private static string uuid() {
  179. nextID++;
  180. return nextID.ToString();
  181. }
  182. public static string addCallback(Delegate callback) {
  183. string uuid = CallbackHandler.uuid();
  184. if (callback != null) {
  185. CallbackInfo callbackInfo = new CallbackInfo();
  186. callbackInfo.callback = callback;
  187. callbackInfo.deadTime = Utility.GetTimestamp() + 10 * 1000;
  188. mapper.Add(uuid, callbackInfo);
  189. }
  190. return uuid;
  191. }
  192. public static void handleCallback(Data data) {
  193. if (mapper.Count > 10) {
  194. long now = Utility.GetTimestamp();
  195. LinkedList<string> outKeys = new LinkedList<string>();
  196. foreach (var item in mapper) {
  197. if (now >= item.Value.deadTime) {
  198. outKeys.AddLast(item.Key);
  199. }
  200. }
  201. foreach (var item in outKeys) {
  202. mapper.Remove(item);
  203. }
  204. }
  205. CallbackInfo callbackInfo;
  206. mapper.TryGetValue(data.uuid, out callbackInfo);
  207. if (callbackInfo != null) {
  208. mapper.Remove(data.uuid);
  209. object target = callbackInfo.callback.Target;
  210. System.Reflection.MethodInfo method = callbackInfo.callback.Method;
  211. Utility.FormatArgsType(data.args, method.GetParameters());
  212. method.Invoke(target, data.args);
  213. }
  214. }
  215. }
  216. class Utility {
  217. public static long GetTimestamp() {
  218. TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
  219. return (long)ts.TotalMilliseconds;
  220. }
  221. public static void FormatArgsType(object[] args, System.Reflection.ParameterInfo[] parameters) {
  222. int i = 0;
  223. foreach (var param in parameters) {
  224. Type type = param.ParameterType;
  225. if (IsBaseType(type)) {
  226. args[i] = Convert.ChangeType(args[i], type);
  227. } else if (args[i].GetType().IsSubclassOf(typeof(JContainer))) {
  228. args[i] = ((JContainer)args[i]).ToObject(type);
  229. }
  230. i++;
  231. }
  232. }
  233. public static bool IsBaseType(Type type) {
  234. if (typeof(System.Int32).Equals(type)) return true;
  235. if (typeof(System.Int64).Equals(type)) return true;
  236. if (typeof(System.Single).Equals(type)) return true;
  237. if (typeof(System.Double).Equals(type)) return true;
  238. if (typeof(System.String).Equals(type)) return true;
  239. if (typeof(System.Boolean).Equals(type)) return true;
  240. return false;
  241. }
  242. }
  243. class CallbackInfo {
  244. public Delegate callback;
  245. public long deadTime;
  246. }
  247. class Data {
  248. public string uuid;
  249. public int type;
  250. public string func;
  251. public object[] args;
  252. }
  253. enum DataType {
  254. EVENT,
  255. FUNCTION,
  256. METHOD
  257. }
  258. }