JCEngine.cs 9.9 KB

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