PomeloClient.cs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. using CommonLang;
  2. using CommonLang.Concurrent;
  3. using CommonLang.IO;
  4. using CommonLang.Log;
  5. using SimpleJson;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.IO;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Threading;
  13. namespace Pomelo.DotNetClient
  14. {
  15. public class PomeloClient : IDisposable
  16. {
  17. //---------------------------------------------------------------------------------------------------------------------
  18. protected readonly CommonLang.Log.Logger log;
  19. private readonly PomeloClientAdapter adapter;
  20. private readonly Listener listener;
  21. private HashMap<uint, RequestHandler> response_map = new HashMap<uint, RequestHandler>();
  22. private HashMap<string, List<PushHandler>> push_handler = new HashMap<string, List<PushHandler>>();
  23. private HashMap<string, PushHandler> push_handler_once = new HashMap<string, PushHandler>();
  24. private readonly AtomicUInt req_id_gen = new AtomicUInt(1);
  25. private readonly SystemTimeInterval<int> request_timer = new SystemTimeInterval<int>(5*1000);
  26. //private readonly SyncMessageQueue<Action> tasks = new SyncMessageQueue<Action>();
  27. private readonly SyncMessageQueue2 tasks;
  28. private readonly ISerializer serializer;
  29. private bool disposed = false;
  30. //---------------------------------------------------------------------------------------------------------------------
  31. // public TypeModel Serializer
  32. // {
  33. // get { return serializer; }
  34. // }
  35. public bool IsDisposed
  36. {
  37. get { return disposed; }
  38. }
  39. public bool IsConnected
  40. {
  41. get { return this.Session != null ? this.Session.Connected : false; }
  42. }
  43. public NetWorkState NetWorkState
  44. {
  45. get { return adapter.NetWorkState; }
  46. }
  47. public long RecvTime
  48. {
  49. get { return adapter.GetPing(); }
  50. }
  51. public long TotalRecvBytes { get { return adapter.TotalRecvBytes; } }
  52. public long TotalSentBytes { get { return adapter.TotalSentBytes; } }
  53. //---------------------------------------------------------------------------------------------------------------------
  54. public Socket Session { get { return adapter.Session; } }
  55. public PomeloClient(ISerializer serializer)
  56. {
  57. this.serializer = serializer;
  58. this.log = LoggerFactory.GetLogger(GetType().Name);
  59. this.listener = new Listener(this);
  60. this.adapter = PomeloClientFactory.Instance.CreateAdapter(listener);
  61. this.tasks = new SyncMessageQueue2(onError);
  62. }
  63. public virtual void QueueTask(Action action)
  64. {
  65. tasks.Enqueue(action);
  66. }
  67. public virtual void ClearQueue()
  68. {
  69. tasks.Clear();
  70. }
  71. //---------------------------------------------------------------------------------------------------------------------
  72. class Listener : IPomeloClientAdapterListener
  73. {
  74. public readonly PomeloClient client;
  75. public Action<JsonObject> connectCallback;
  76. public Listener(PomeloClient c)
  77. {
  78. this.client = c;
  79. }
  80. public void OnConnected(Socket session, JsonObject user)
  81. {
  82. if (connectCallback != null)
  83. {
  84. connectCallback(user);
  85. }
  86. }
  87. public void OnError(Exception err)
  88. {
  89. if(client != null)
  90. {
  91. client.onError(err);
  92. }
  93. }
  94. public void OnNetWorkStateChanged(NetWorkState st)
  95. {
  96. if (client != null && client.event_NetWorkStateChangedEvent != null)
  97. {
  98. client.event_NetWorkStateChangedEvent(st);
  99. }
  100. }
  101. public void OnDisconnected(Socket session, string reason)
  102. {
  103. client.clear_response(true);
  104. if (client.event_OnDisconnected != null)
  105. {
  106. client.event_OnDisconnected.Invoke(reason);
  107. }
  108. }
  109. public void OnReceivedMessage(RecvMessage msg)
  110. {
  111. client.process_message(msg);
  112. }
  113. public void ClearQueue()
  114. {
  115. client.ClearQueue();
  116. }
  117. }
  118. /// <summary>
  119. /// 网络连接
  120. /// </summary>
  121. /// <param name="host"></param>
  122. /// <param name="port"></param>
  123. /// <param name="timeout"></param>
  124. /// <param name="user"></param>
  125. /// <param name="connectCallback"></param>
  126. public void connect(string host, int port, int timeout, JsonObject user, Action<JsonObject> connectCallback)
  127. {
  128. this.listener.connectCallback = connectCallback;
  129. this.request_timer.Tag = timeout;
  130. this.adapter.connect(host, port, timeout, user);
  131. }
  132. /// <summary>
  133. /// 网络连接
  134. /// </summary>
  135. /// <param name="host"></param>
  136. /// <param name="port"></param>
  137. /// <param name="timeout"></param>
  138. /// <param name="connectCallback"></param>
  139. public void connect(string host, int port, int timeout, Action<JsonObject> connectCallback)
  140. {
  141. this.listener.connectCallback = connectCallback;
  142. this.request_timer.Tag = timeout;
  143. this.adapter.connect(host, port, timeout, null);
  144. }
  145. /// <summary>
  146. /// 主动断开连接
  147. /// </summary>
  148. public void disconnect()
  149. {
  150. log.Debug("====socket ==PomeloClient== disconnect ThreadID:"+Thread.CurrentThread.ManagedThreadId);
  151. adapter.disconnect();
  152. this.clear_response(false);
  153. }
  154. protected void disposing()
  155. {
  156. adapter.disposing();
  157. this.ClearLastResponse();
  158. this.clear_response(false);
  159. this.clear_push();
  160. ClearQueue();
  161. //tasks.ProcessMessages();
  162. }
  163. //---------------------------------------------------------------------------------------------------------------------
  164. /// <summary>
  165. /// 心跳,客户端一般是一帧调用一次
  166. /// </summary>
  167. public virtual void update(float deltime)
  168. {
  169. tasks.ProcessMessages();
  170. adapter.update(deltime);
  171. check_request_timeout();
  172. }
  173. public void DoSendUpdate()
  174. {
  175. adapter.DoSendUpdate();
  176. }
  177. //---------------------------------------------------------------------------------------------------------------------
  178. /// <summary>
  179. /// 发送请求消息
  180. /// </summary>
  181. public void request_binary(string route, byte[] data, Action<PomeloException, byte[]> action)
  182. {
  183. uint id = req_id_gen.GetAndIncrement();
  184. this.listen_response_binary(id, route, action);
  185. try
  186. {
  187. this.send(route, id, data);
  188. }
  189. catch (Exception e)
  190. {
  191. onError(e);
  192. }
  193. }
  194. /// <summary>
  195. /// 发送请求消息
  196. /// </summary>
  197. public void request(string route, object msg, Action<PomeloException, object> action)
  198. {
  199. uint id = req_id_gen.GetAndIncrement();
  200. this.listen_response(id, route, action, null);
  201. try
  202. {
  203. this.send(route, id, msg);
  204. }
  205. catch (Exception e)
  206. {
  207. onError(e);
  208. }
  209. }
  210. /// <summary>
  211. /// 发送请求消息并匹配编/解码器
  212. /// </summary>
  213. public void request(string route, object msg, Action<PomeloException, object> action, MessageEncoder encoder, MessageDecoder decoder)
  214. {
  215. uint id = req_id_gen.GetAndIncrement();
  216. this.listen_response(id, route, action, decoder);
  217. try
  218. {
  219. this.send(route, id, msg, encoder);
  220. }
  221. catch (Exception e)
  222. {
  223. onError(e);
  224. }
  225. }
  226. /// <summary>
  227. /// 发送请求消息并匹配编/解码器
  228. /// </summary>
  229. public void request(string route, object msg, Action<PomeloException, object> action, MessageEncoder encoder, MessageDecoder decoder, object option)
  230. {
  231. this.onRequestStart(route, option);
  232. this.request(route, msg, (err, response) =>
  233. {
  234. this.onRequestEnd(route, err, response, option);
  235. action(err, response);
  236. },
  237. encoder, decoder);
  238. }
  239. /// <summary>
  240. /// 发送请求并验证
  241. /// </summary>
  242. public void request(object req, ResponseValidater validate, Action<PomeloException, object> cb, object option = null)
  243. {
  244. var route = EventTypes.GetRequestKey(req.GetType());
  245. Type responseType = EventTypes.GetResponseType(route);
  246. this.onRequestStart(route, option);
  247. this.request(route, req, (err, response) =>
  248. {
  249. if (err != null)
  250. {
  251. this.onRequestEnd(route, err, null, option);
  252. cb(err, null);
  253. }
  254. else if (response != null)
  255. {
  256. int s2c_code;
  257. string s2c_msg;
  258. if (validate(response, out s2c_code, out s2c_msg))
  259. {
  260. this.onRequestEnd(route, null, response, option);
  261. cb(null, response);
  262. }
  263. else
  264. {
  265. PomeloException exp = new PomeloException(s2c_code, s2c_msg);
  266. exp.Route = route;
  267. this.onRequestEnd(route, exp, null, option);
  268. cb(exp, null);
  269. }
  270. }
  271. });
  272. }
  273. /// <summary>
  274. /// 发送请求消息
  275. /// </summary>
  276. public void request(object req, Action<PomeloException, object> cb, object option = null)
  277. {
  278. this.request(req,
  279. (object rsp, out int s2c_code, out string s2c_msg) => { s2c_code = 200; s2c_msg = null; return true; },
  280. cb, option);
  281. }
  282. /// <summary>
  283. /// 发送请求消息
  284. /// </summary>
  285. public void request<RSP>(object req, ResponseValidater validate, Action<PomeloException, RSP> cb, object option = null)
  286. where RSP : class
  287. {
  288. this.request(req,
  289. (object rsp, out int s2c_code, out string s2c_msg) => { return validate(rsp as RSP, out s2c_code, out s2c_msg); },
  290. (err, rsp) => { cb(err, rsp as RSP); }, option);
  291. }
  292. /// <summary>
  293. /// 发送请求消息
  294. /// </summary>
  295. public void request<RSP>(object req, Action<PomeloException, RSP> cb, object option = null)
  296. where RSP : class
  297. {
  298. this.request(req,
  299. (object rsp, out int s2c_code, out string s2c_msg) => { s2c_code = 200; s2c_msg = null; return true; },
  300. (err, rsp) => { cb(err, rsp as RSP); }, option);
  301. }
  302. //-----------------------------------------------------------------------------------------------------------------
  303. /// <summary>
  304. /// 发送通知消息
  305. /// </summary>
  306. public void notify(string route, object msg, MessageEncoder encoder)
  307. {
  308. this.send(route, 0, msg, encoder);
  309. }
  310. /// <summary>
  311. /// 发送通知消息
  312. /// </summary>
  313. public void notify_binary(string route, byte[] data)
  314. {
  315. this.send(route, 0, data);
  316. }
  317. /// <summary>
  318. /// 发送通知消息
  319. /// </summary>
  320. public void notify(object msg)
  321. {
  322. var route = EventTypes.GetNotifyKey(msg.GetType());
  323. this.send(route, 0, msg);
  324. }
  325. //-----------------------------------------------------------------------------------------------------------------
  326. /// <summary>
  327. /// 注册事件回调
  328. /// </summary>
  329. public PushHandler listen<T>(Action<T> action) where T : class
  330. {
  331. var route = EventTypes.GetPushKey(typeof(T));
  332. if (route != null)
  333. {
  334. return listen_push(route, (push) => { action(push as T); }, null);
  335. }
  336. return null;
  337. }
  338. /// <summary>
  339. /// 注册事件回调
  340. /// </summary>
  341. public PushHandler listen(string route, Action<object> action)
  342. {
  343. return listen_push(route, action, null);
  344. }
  345. /// <summary>
  346. /// 注册事件回调
  347. /// </summary>
  348. public PushHandler listen(string route, Action<object> action, MessageDecoder decoder)
  349. {
  350. return listen_push(route, action, decoder);
  351. }
  352. /// <summary>
  353. /// 注册事件回调
  354. /// </summary>
  355. public PushHandler listen_binary(string route, Action<byte[]> action)
  356. {
  357. return listen_push_binary(route, action);
  358. }
  359. /// <summary>
  360. /// 注册事件回调(如果之前有监听,则替换)
  361. /// </summary>
  362. public void listen_once<T>(Action<T> action) where T : class
  363. {
  364. var route = EventTypes.GetPushKey(typeof(T));
  365. if (route != null)
  366. {
  367. listen_push_once(route, (push) => { action(push as T); }, null);
  368. }
  369. }
  370. /// <summary>
  371. /// 注册事件回调(如果之前有监听,则替换)
  372. /// </summary>
  373. public void listen_once(string route, Action<object> action)
  374. {
  375. listen_push_once(route, action, null);
  376. }
  377. /// <summary>
  378. /// 注册事件回调(如果之前有监听,则替换)
  379. /// </summary>
  380. public void listen_once(string route, Action<object> action, MessageDecoder decoder)
  381. {
  382. listen_push_once(route, action, decoder);
  383. }
  384. /// <summary>
  385. /// 注册事件回调(如果之前有监听,则替换)
  386. /// </summary>
  387. public void listen_once_binary(string route, Action<byte[]> action)
  388. {
  389. listen_push_once_binary(route, action);
  390. }
  391. //-----------------------------------------------------------------------------------------------------------------
  392. #region ProcessMessages
  393. protected void send(string route, uint id, object msg)
  394. {
  395. try
  396. {
  397. SendMessage send_object;
  398. #if LOCK_SERIALIZER
  399. //lock (this.serializer)
  400. #endif
  401. {
  402. send_object = SendMessage.Alloc(route, id, this.serializer, msg);
  403. }
  404. adapter.send(send_object);
  405. }
  406. catch (Exception err) { onError(err); }
  407. }
  408. public void send(SendMessage msg)
  409. {
  410. try
  411. {
  412. adapter.send(msg);
  413. }
  414. catch (Exception err)
  415. {
  416. onError(err);
  417. }
  418. }
  419. public void send(string route, uint id, MemoryStream stream)
  420. {
  421. try
  422. {
  423. var send_object = SendMessage.Alloc(route, id, stream);
  424. adapter.send(send_object);
  425. }
  426. catch (Exception err)
  427. {
  428. onError(err);
  429. }
  430. }
  431. protected void send(string route, uint id, object msg, MessageEncoder encoder)
  432. {
  433. try
  434. {
  435. var send_object = SendMessage.Alloc(route, id, msg, encoder);
  436. adapter.send(send_object);
  437. }
  438. catch (Exception err) { onError(err); }
  439. }
  440. protected void send(string route, uint id, byte[] data)
  441. {
  442. try
  443. {
  444. var send_object = SendMessage.Alloc(route, id, data);
  445. adapter.send(send_object);
  446. }
  447. catch (Exception err) { onError(err); }
  448. }
  449. protected virtual void process_message(RecvMessage msg)
  450. {
  451. if (event_NetWorkHandlePushImmediately != null)
  452. {
  453. if (event_NetWorkHandlePushImmediately(msg.Route, msg.Stream))
  454. {
  455. //log.Debug("socket ===== event_NetWorkHandlePushImmediately msg.Route: " + msg.Route);
  456. return;
  457. }
  458. }
  459. try
  460. {
  461. if (msg.PkgType == PackageType.PKG_HEARTBEAT)
  462. {
  463. if (event_OnHeartBeat != null)
  464. {
  465. event_OnHeartBeat.Invoke();
  466. }
  467. return;
  468. }
  469. if (msg.MsgType == MessageType.MSG_RESPONSE)
  470. {
  471. process_response(msg);
  472. }
  473. else if (msg.MsgType == MessageType.MSG_PUSH)
  474. {
  475. process_push(msg);
  476. }
  477. }
  478. catch (Exception err)
  479. {
  480. log.Error("====== PomeloClient.process_message() exception:" + err.StackTrace);
  481. onError(err);
  482. }
  483. }
  484. private void check_request_timeout()
  485. {
  486. if (request_timer.Update())
  487. {
  488. using (var removing = ListObjectPool<RequestHandler>.AllocAutoRelease())
  489. using (var list = ListObjectPool<KeyValuePair<uint, RequestHandler>>.AllocAutoRelease())
  490. {
  491. long cur_time = CUtils.CurrentTimeMS;
  492. if (response_map.Count > 0)
  493. {
  494. list.AddRange(response_map);
  495. foreach (var req in list)
  496. {
  497. if (req.Value.CheckTimeout(request_timer.Tag, cur_time))
  498. {
  499. response_map.Remove(req.Key);
  500. removing.Add(req.Value);
  501. }
  502. }
  503. }
  504. else
  505. {
  506. return;
  507. }
  508. if (removing.Count > 0)
  509. {
  510. foreach (var r in removing)
  511. {
  512. PomeloException exp = new PomeloException(408, "Request Timeout : " + r.Route);
  513. exp.Route = r.Route;
  514. exp.Timeout = true;
  515. r.Invoke(exp);
  516. log.Error("socket ====== check_request_timeout exp.Route "+ exp.Route);
  517. }
  518. }
  519. }
  520. }
  521. }
  522. private void clear_response(bool async)
  523. {
  524. response_map.Clear();
  525. //using (var cbs = ListObjectPool<RequestHandler>.AllocAutoRelease())
  526. //{
  527. // lock (response_map)
  528. // {
  529. // if (response_map.Count > 0)
  530. // {
  531. // log.Debug("===========socket listen_response Clear All");
  532. // cbs.AddRange(response_map.Values);
  533. // response_map.Clear();
  534. // }
  535. // else
  536. // {
  537. // return;
  538. // }
  539. // }
  540. // foreach (var cb in cbs)
  541. // {
  542. // var err = new PomeloException(-1, "closed");
  543. // err.Route = cb.Route;
  544. // if (async)
  545. // {
  546. // QueueTask(() =>
  547. // {
  548. // cb.Invoke(err);
  549. // });
  550. // }
  551. // else
  552. // {
  553. // cb.Invoke(err);
  554. // }
  555. // }
  556. //}
  557. }
  558. private void listen_response(uint id, string route, Action<PomeloException, object> cb, MessageDecoder dc)
  559. {
  560. //log.Debug("socekt listen_response 1 ThreadID: " + Thread.CurrentThread.ManagedThreadId);
  561. if (id > 0 && cb != null)
  562. {
  563. //log.Debug("===========socket listen_response Add msgid:" + id);
  564. this.response_map.Add(id, new RequestHandler(this, route, cb, null, dc));
  565. }
  566. }
  567. private void listen_response_binary(uint id, string route, Action<PomeloException, byte[]> cb)
  568. {
  569. //log.Debug("socekt listen_response 2 ThreadID: " + Thread.CurrentThread.ManagedThreadId);
  570. if (id > 0 && cb != null)
  571. {
  572. //log.Debug("===========socket listen_response_binary Add msgid:" + id);
  573. this.response_map.Add(id, new RequestHandler(this, route, null, cb, null));
  574. }
  575. }
  576. protected virtual void process_response(RecvMessage msg)
  577. {
  578. RequestHandler cb;
  579. //log.Debug("lixu===========socket process_response msgid:" + msg.MsgID);
  580. if (!response_map.TryGetValue(msg.MsgID, out cb))
  581. {
  582. log.WarnFormat("Ignore response message : {0}", msg.MsgID);
  583. return;
  584. }
  585. response_map.Remove(msg.MsgID);
  586. try
  587. {
  588. //log.Debug("socket ===== process_response msg.Route: " + cb.Route);
  589. msg.Route = cb.Route;
  590. var output = msg.Stream;
  591. if (cb.IsBinary)
  592. {
  593. var response = msg.ReadBody();
  594. cb.InvokeBin(response);
  595. }
  596. else if (cb.Decoder != null)
  597. {
  598. var response = msg.ReadBody(cb.Decoder);
  599. if (response == null)
  600. {
  601. throw new Exception("Decode response error : " + msg.Route);
  602. }
  603. if (response is PomeloException)
  604. {
  605. cb.Invoke(response as PomeloException);
  606. }
  607. else
  608. {
  609. cb.Invoke(response);
  610. }
  611. }
  612. else
  613. {
  614. Type responseType = EventTypes.GetResponseType(msg.Route);
  615. if (responseType == null)
  616. {
  617. throw new Exception("No response type : " + msg.Route);
  618. }
  619. object response;
  620. //lock (this.serializer)
  621. {
  622. response = msg.ReadBody(this.serializer, responseType);
  623. }
  624. if (response == null)
  625. {
  626. throw new Exception("Deserialize response error : " + responseType);
  627. }
  628. else
  629. {
  630. this.addLastResponse(response);
  631. cb.Invoke(response);
  632. }
  633. }
  634. }
  635. catch (Exception e)
  636. {
  637. var exp = new PomeloException(501, e.Message, e);
  638. exp.Route = msg.Route;
  639. cb.Invoke(exp);
  640. onError(e);
  641. }
  642. }
  643. private PushHandler listen_push(string route, Action<object> cb, MessageDecoder dc)
  644. {
  645. var ret = new PushHandler(this, route, cb, dc);
  646. var act = push_handler.Get(route);
  647. if (act == null)
  648. {
  649. act = new List<PushHandler>();
  650. push_handler.Put(route, act);
  651. }
  652. act.Add(ret);
  653. return ret;
  654. }
  655. private void listen_push_once(string route, Action<object> cb, MessageDecoder dc)
  656. {
  657. //lock (push_handler_once)
  658. {
  659. if (cb == null)
  660. {
  661. push_handler_once.Remove(route);
  662. }
  663. else
  664. {
  665. push_handler_once.Put(route, new PushHandler(this, route, cb, dc));
  666. }
  667. }
  668. }
  669. private PushHandler listen_push_binary(string route, Action<byte[]> cb)
  670. {
  671. var ret = new PushHandler(this, route, cb);
  672. var act = push_handler.Get(route);
  673. if (act == null)
  674. {
  675. act = new List<PushHandler>();
  676. push_handler.Put(route, act);
  677. }
  678. act.Add(ret);
  679. return ret;
  680. }
  681. private void listen_push_once_binary(string route, Action<byte[]> cb)
  682. {
  683. if (cb == null)
  684. {
  685. push_handler_once.Remove(route);
  686. }
  687. else
  688. {
  689. push_handler_once.Put(route, new PushHandler(this, route, cb));
  690. }
  691. }
  692. internal void remove_push(PushHandler handler)
  693. {
  694. var act = push_handler.Get(handler.Route);
  695. if (act != null)
  696. {
  697. act.Remove(handler);
  698. }
  699. }
  700. protected virtual void process_push(RecvMessage msg)
  701. {
  702. try
  703. {
  704. using (var all = ListObjectPool<PushHandler>.AllocAutoRelease())
  705. {
  706. //log.Debug("socket ===== process_push msg.Route: " + msg.Route);
  707. //lock (push_handler)
  708. {
  709. var list = push_handler.Get(msg.Route);
  710. if (list != null) { all.AddRange(list); }
  711. }
  712. //lock (push_handler_once)
  713. {
  714. var once = push_handler_once.Get(msg.Route);
  715. if (once != null) all.Add(once);
  716. }
  717. if (all.Count > 0)
  718. {
  719. object push = null;
  720. byte[] push_bin = null;
  721. var push_type = EventTypes.GetPushType(msg.Route);
  722. for (int i = 0; i < all.Count; i++)
  723. {
  724. var handler = all[i];
  725. if (handler.IsBinary)
  726. {
  727. if (push_bin == null)
  728. push_bin = msg.ReadBody();
  729. handler.InvokeBin(push_bin);
  730. }
  731. else if (handler.decoder != null)
  732. {
  733. var decode = msg.ReadBody(handler.decoder);
  734. if (decode != null)
  735. {
  736. handler.Invoke(decode);
  737. }
  738. }
  739. else
  740. {
  741. if (push == null)
  742. {
  743. if (push_type != null)
  744. {
  745. //lock (this.serializer)
  746. {
  747. push = msg.ReadBody(this.serializer, push_type);
  748. }
  749. }
  750. }
  751. if (push != null)
  752. {
  753. this.addLastResponse(push);
  754. handler.Invoke(push);
  755. }
  756. }
  757. }
  758. }
  759. else
  760. {
  761. if (event_NetWorkHandlePush != null)
  762. {
  763. event_NetWorkHandlePush.Invoke(msg.Route, msg.Stream);
  764. }
  765. }
  766. }
  767. }
  768. catch (Exception e)
  769. {
  770. log.Error("Decode Error: route = " + msg.Route + "\n" + e.Message);
  771. onError(e);
  772. }
  773. }
  774. private void clear_push()
  775. {
  776. //lock (push_handler)
  777. {
  778. push_handler.Clear();
  779. }
  780. //lock (push_handler_once)
  781. {
  782. push_handler_once.Clear();
  783. }
  784. }
  785. #endregion
  786. //-----------------------------------------------------------------------------------------------------------------
  787. #region LastResponse
  788. private bool enable_last_response = true;
  789. private readonly HashMap<Type, object> last_response = new HashMap<Type, object>();
  790. public bool IsSaveResponse
  791. {
  792. get { return enable_last_response; }
  793. set
  794. {
  795. enable_last_response = value;
  796. if (value == false)
  797. {
  798. //lock (last_response)
  799. {
  800. last_response.Clear();
  801. }
  802. }
  803. }
  804. }
  805. internal void addLastResponse(object push)
  806. {
  807. //lock (last_response)
  808. {
  809. if (push != null && enable_last_response)
  810. {
  811. last_response.Put(push.GetType(), push);
  812. }
  813. }
  814. }
  815. public T GetLastResponse<T>() where T : class
  816. {
  817. //lock (last_response)
  818. {
  819. return last_response.Get(typeof(T)) as T;
  820. }
  821. }
  822. public object GetLastResponse(Type type)
  823. {
  824. //lock (last_response)
  825. {
  826. return last_response.Get(type);
  827. }
  828. }
  829. public void ClearLastResponse()
  830. {
  831. //lock (last_response)
  832. {
  833. last_response.Clear();
  834. }
  835. }
  836. #endregion
  837. //-----------------------------------------------------------------------------------------------------------------
  838. internal void onError(Exception err)
  839. {
  840. if (event_OnError != null) { event_OnError.Invoke(err); }
  841. }
  842. //-----------------------------------------------------------------------------------------------------------------
  843. public void onRequestStart(string route, object option)
  844. {
  845. if (event_RequestStartEvent != null)
  846. {
  847. event_RequestStartEvent(route, option);
  848. }
  849. }
  850. public void onRequestEnd(string route, PomeloException excep, object response, object option)
  851. {
  852. if (event_RequestEndEvent != null)
  853. {
  854. event_RequestEndEvent(route, excep, response, option);
  855. }
  856. }
  857. //-----------------------------------------------------------------------------------------------------------------
  858. public void Dispose()
  859. {
  860. if (this.disposed)
  861. return;
  862. this.disposing();
  863. this.disposing_events();
  864. this.disposed = true;
  865. }
  866. //-----------------------------------------------------------------------------------------------------------------
  867. /// <summary>
  868. /// 网络变更事件
  869. /// </summary>
  870. public event Action<NetWorkState> NetWorkStateChangedEvent
  871. {
  872. add { /*lock (this)*/ event_NetWorkStateChangedEvent += value; }
  873. remove { /*lock (this)*/ event_NetWorkStateChangedEvent -= value; }
  874. }
  875. /// <summary>
  876. /// 网络线程立即回调收到消息
  877. /// </summary>
  878. public event ProcessMessageImmediately NetWorkHandlePushImmediately
  879. {
  880. add { /*lock (this)*/ event_NetWorkHandlePushImmediately += value; }
  881. remove { /*lock (this)*/ event_NetWorkHandlePushImmediately -= value; }
  882. }
  883. /// <summary>
  884. /// 错误回调
  885. /// </summary>
  886. public event Action<Exception> OnError
  887. {
  888. add { /*lock (this)*/ event_OnError += value; }
  889. remove { /*lock (this)*/ event_OnError -= value; }
  890. }
  891. /// <summary>
  892. /// 主线程回调收到未处理消息
  893. /// </summary>
  894. public event Action<string, Stream> NetWorkHandlePush
  895. {
  896. add { /*lock (this)*/ event_NetWorkHandlePush += value; }
  897. remove { /*lock (this)*/ event_NetWorkHandlePush -= value; }
  898. }
  899. /// <summary>
  900. /// 请求开始事件
  901. /// </summary>
  902. public event Action<string, object> RequestStartEvent
  903. {
  904. add { /*lock (this)*/ event_RequestStartEvent += value; }
  905. remove { /*lock (this)*/ event_RequestStartEvent -= value; }
  906. }
  907. /// <summary>
  908. /// 请求返回事件
  909. /// </summary>
  910. public event Action<string, PomeloException, object, object> RequestEndEvent
  911. {
  912. add { /*lock (this)*/ event_RequestEndEvent += value; }
  913. remove { /*lock (this)*/ event_RequestEndEvent -= value; }
  914. }
  915. /// <summary>
  916. /// 已断线
  917. /// </summary>
  918. public event Action<string> OnDisconnected
  919. {
  920. add { /*lock (this)*/ event_OnDisconnected += value; }
  921. remove { /*lock (this)*/ event_OnDisconnected -= value; }
  922. }
  923. /// <summary>
  924. /// 用于Gate心跳包
  925. /// </summary>
  926. public event Action OnHeartBeat
  927. {
  928. add { /*lock (this)*/ event_OnHeartBeat += value; }
  929. remove { /*lock (this)*/ event_OnHeartBeat -= value; }
  930. }
  931. private Action<Exception> event_OnError;
  932. private Action<string, object> event_RequestStartEvent;
  933. private Action<string, PomeloException, object, object> event_RequestEndEvent;
  934. private Action<NetWorkState> event_NetWorkStateChangedEvent;
  935. private Action<string> event_OnDisconnected;
  936. private Action<string, Stream> event_NetWorkHandlePush;
  937. private ProcessMessageImmediately event_NetWorkHandlePushImmediately;
  938. private Action event_OnHeartBeat;
  939. protected virtual void disposing_events()
  940. {
  941. event_OnError = null;
  942. event_RequestStartEvent = null;
  943. event_RequestEndEvent = null;
  944. event_NetWorkStateChangedEvent = null;
  945. event_OnDisconnected = null;
  946. event_NetWorkHandlePush = null;
  947. event_NetWorkHandlePushImmediately = null;
  948. event_OnHeartBeat = null;
  949. }
  950. //-----------------------------------------------------------------------------------------------------------------
  951. }
  952. }