12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037 |
- using CommonLang;
- using CommonLang.Concurrent;
- using CommonLang.IO;
- using CommonLang.Log;
- using SimpleJson;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- namespace Pomelo.DotNetClient
- {
- public class PomeloClient : IDisposable
- {
-
- protected readonly CommonLang.Log.Logger log;
- private readonly PomeloClientAdapter adapter;
- private readonly Listener listener;
- private HashMap<uint, RequestHandler> response_map = new HashMap<uint, RequestHandler>();
- private HashMap<string, List<PushHandler>> push_handler = new HashMap<string, List<PushHandler>>();
- private HashMap<string, PushHandler> push_handler_once = new HashMap<string, PushHandler>();
- private readonly AtomicUInt req_id_gen = new AtomicUInt(1);
- private readonly SystemTimeInterval<int> request_timer = new SystemTimeInterval<int>(5*1000);
-
- private readonly SyncMessageQueue2 tasks;
- private readonly ISerializer serializer;
- private bool disposed = false;
-
-
-
-
-
- public bool IsDisposed
- {
- get { return disposed; }
- }
- public bool IsConnected
- {
- get { return this.Session != null ? this.Session.Connected : false; }
- }
- public NetWorkState NetWorkState
- {
- get { return adapter.NetWorkState; }
- }
- public long RecvTime
- {
- get { return adapter.GetPing(); }
- }
- public long TotalRecvBytes { get { return adapter.TotalRecvBytes; } }
- public long TotalSentBytes { get { return adapter.TotalSentBytes; } }
-
- public Socket Session { get { return adapter.Session; } }
- public PomeloClient(ISerializer serializer)
- {
- this.serializer = serializer;
- this.log = LoggerFactory.GetLogger(GetType().Name);
- this.listener = new Listener(this);
- this.adapter = PomeloClientFactory.Instance.CreateAdapter(listener);
- this.tasks = new SyncMessageQueue2(onError);
- }
- public virtual void QueueTask(Action action)
- {
- tasks.Enqueue(action);
- }
- public virtual void ClearQueue()
- {
- tasks.Clear();
- }
-
- class Listener : IPomeloClientAdapterListener
- {
- public readonly PomeloClient client;
- public Action<JsonObject> connectCallback;
- public Listener(PomeloClient c)
- {
- this.client = c;
- }
- public void OnConnected(Socket session, JsonObject user)
- {
- if (connectCallback != null)
- {
- connectCallback(user);
- }
- }
- public void OnError(Exception err)
- {
- if(client != null)
- {
- client.onError(err);
- }
- }
- public void OnNetWorkStateChanged(NetWorkState st)
- {
- if (client != null && client.event_NetWorkStateChangedEvent != null)
- {
- client.event_NetWorkStateChangedEvent(st);
- }
- }
- public void OnDisconnected(Socket session, string reason)
- {
- client.clear_response(true);
- if (client.event_OnDisconnected != null)
- {
- client.event_OnDisconnected.Invoke(reason);
- }
- }
- public void OnReceivedMessage(RecvMessage msg)
- {
- client.process_message(msg);
- }
- public void ClearQueue()
- {
- client.ClearQueue();
- }
- }
-
-
-
-
-
-
-
-
- public void connect(string host, int port, int timeout, JsonObject user, Action<JsonObject> connectCallback)
- {
- this.listener.connectCallback = connectCallback;
- this.request_timer.Tag = timeout;
- this.adapter.connect(host, port, timeout, user);
- }
-
-
-
-
-
-
-
- public void connect(string host, int port, int timeout, Action<JsonObject> connectCallback)
- {
- this.listener.connectCallback = connectCallback;
- this.request_timer.Tag = timeout;
- this.adapter.connect(host, port, timeout, null);
- }
-
-
-
- public void disconnect()
- {
- log.Debug("====socket ==PomeloClient== disconnect ThreadID:"+Thread.CurrentThread.ManagedThreadId);
- adapter.disconnect();
- this.clear_response(false);
- }
- protected void disposing()
- {
- adapter.disposing();
- this.ClearLastResponse();
- this.clear_response(false);
- this.clear_push();
- ClearQueue();
-
- }
-
-
-
-
- public virtual void update(float deltime)
- {
- tasks.ProcessMessages();
- adapter.update(deltime);
- check_request_timeout();
- }
- public void DoSendUpdate()
- {
- adapter.DoSendUpdate();
- }
-
-
-
-
- public void request_binary(string route, byte[] data, Action<PomeloException, byte[]> action)
- {
- uint id = req_id_gen.GetAndIncrement();
- this.listen_response_binary(id, route, action);
- try
- {
- this.send(route, id, data);
- }
- catch (Exception e)
- {
- onError(e);
- }
- }
-
-
-
- public void request(string route, object msg, Action<PomeloException, object> action)
- {
- uint id = req_id_gen.GetAndIncrement();
- this.listen_response(id, route, action, null);
- try
- {
- this.send(route, id, msg);
- }
- catch (Exception e)
- {
- onError(e);
- }
- }
-
-
-
- public void request(string route, object msg, Action<PomeloException, object> action, MessageEncoder encoder, MessageDecoder decoder)
- {
- uint id = req_id_gen.GetAndIncrement();
- this.listen_response(id, route, action, decoder);
- try
- {
- this.send(route, id, msg, encoder);
- }
- catch (Exception e)
- {
- onError(e);
- }
- }
-
-
-
- public void request(string route, object msg, Action<PomeloException, object> action, MessageEncoder encoder, MessageDecoder decoder, object option)
- {
- this.onRequestStart(route, option);
- this.request(route, msg, (err, response) =>
- {
- this.onRequestEnd(route, err, response, option);
- action(err, response);
- },
- encoder, decoder);
- }
-
-
-
- public void request(object req, ResponseValidater validate, Action<PomeloException, object> cb, object option = null)
- {
- var route = EventTypes.GetRequestKey(req.GetType());
- Type responseType = EventTypes.GetResponseType(route);
- this.onRequestStart(route, option);
- this.request(route, req, (err, response) =>
- {
- if (err != null)
- {
- this.onRequestEnd(route, err, null, option);
- cb(err, null);
- }
- else if (response != null)
- {
- int s2c_code;
- string s2c_msg;
- if (validate(response, out s2c_code, out s2c_msg))
- {
- this.onRequestEnd(route, null, response, option);
- cb(null, response);
- }
- else
- {
- PomeloException exp = new PomeloException(s2c_code, s2c_msg);
- exp.Route = route;
- this.onRequestEnd(route, exp, null, option);
- cb(exp, null);
- }
- }
- });
- }
-
-
-
- public void request(object req, Action<PomeloException, object> cb, object option = null)
- {
- this.request(req,
- (object rsp, out int s2c_code, out string s2c_msg) => { s2c_code = 200; s2c_msg = null; return true; },
- cb, option);
- }
-
-
-
- public void request<RSP>(object req, ResponseValidater validate, Action<PomeloException, RSP> cb, object option = null)
- where RSP : class
- {
- this.request(req,
- (object rsp, out int s2c_code, out string s2c_msg) => { return validate(rsp as RSP, out s2c_code, out s2c_msg); },
- (err, rsp) => { cb(err, rsp as RSP); }, option);
- }
-
-
-
- public void request<RSP>(object req, Action<PomeloException, RSP> cb, object option = null)
- where RSP : class
- {
- this.request(req,
- (object rsp, out int s2c_code, out string s2c_msg) => { s2c_code = 200; s2c_msg = null; return true; },
- (err, rsp) => { cb(err, rsp as RSP); }, option);
- }
-
-
-
-
- public void notify(string route, object msg, MessageEncoder encoder)
- {
- this.send(route, 0, msg, encoder);
- }
-
-
-
- public void notify_binary(string route, byte[] data)
- {
- this.send(route, 0, data);
- }
-
-
-
- public void notify(object msg)
- {
- var route = EventTypes.GetNotifyKey(msg.GetType());
- this.send(route, 0, msg);
- }
-
-
-
-
- public PushHandler listen<T>(Action<T> action) where T : class
- {
- var route = EventTypes.GetPushKey(typeof(T));
- if (route != null)
- {
- return listen_push(route, (push) => { action(push as T); }, null);
- }
- return null;
- }
-
-
-
- public PushHandler listen(string route, Action<object> action)
- {
- return listen_push(route, action, null);
- }
-
-
-
- public PushHandler listen(string route, Action<object> action, MessageDecoder decoder)
- {
- return listen_push(route, action, decoder);
- }
-
-
-
- public PushHandler listen_binary(string route, Action<byte[]> action)
- {
- return listen_push_binary(route, action);
- }
-
-
-
- public void listen_once<T>(Action<T> action) where T : class
- {
- var route = EventTypes.GetPushKey(typeof(T));
- if (route != null)
- {
- listen_push_once(route, (push) => { action(push as T); }, null);
- }
- }
-
-
-
- public void listen_once(string route, Action<object> action)
- {
- listen_push_once(route, action, null);
- }
-
-
-
- public void listen_once(string route, Action<object> action, MessageDecoder decoder)
- {
- listen_push_once(route, action, decoder);
- }
-
-
-
- public void listen_once_binary(string route, Action<byte[]> action)
- {
- listen_push_once_binary(route, action);
- }
-
- #region ProcessMessages
- protected void send(string route, uint id, object msg)
- {
- try
- {
- SendMessage send_object;
- #if LOCK_SERIALIZER
-
- #endif
- {
- send_object = SendMessage.Alloc(route, id, this.serializer, msg);
- }
- adapter.send(send_object);
- }
- catch (Exception err) { onError(err); }
- }
- public void send(SendMessage msg)
- {
- try
- {
- adapter.send(msg);
- }
- catch (Exception err)
- {
- onError(err);
- }
- }
- public void send(string route, uint id, MemoryStream stream)
- {
- try
- {
- var send_object = SendMessage.Alloc(route, id, stream);
- adapter.send(send_object);
- }
- catch (Exception err)
- {
- onError(err);
- }
- }
- protected void send(string route, uint id, object msg, MessageEncoder encoder)
- {
- try
- {
- var send_object = SendMessage.Alloc(route, id, msg, encoder);
- adapter.send(send_object);
- }
- catch (Exception err) { onError(err); }
- }
- protected void send(string route, uint id, byte[] data)
- {
- try
- {
- var send_object = SendMessage.Alloc(route, id, data);
- adapter.send(send_object);
- }
- catch (Exception err) { onError(err); }
- }
- protected virtual void process_message(RecvMessage msg)
- {
- if (event_NetWorkHandlePushImmediately != null)
- {
- if (event_NetWorkHandlePushImmediately(msg.Route, msg.Stream))
- {
-
- return;
- }
- }
- try
- {
- if (msg.PkgType == PackageType.PKG_HEARTBEAT)
- {
- if (event_OnHeartBeat != null)
- {
- event_OnHeartBeat.Invoke();
- }
- return;
- }
- if (msg.MsgType == MessageType.MSG_RESPONSE)
- {
- process_response(msg);
- }
- else if (msg.MsgType == MessageType.MSG_PUSH)
- {
- process_push(msg);
- }
- }
- catch (Exception err)
- {
- log.Error("====== PomeloClient.process_message() exception:" + err.StackTrace);
- onError(err);
- }
- }
- private void check_request_timeout()
- {
- if (request_timer.Update())
- {
- using (var removing = ListObjectPool<RequestHandler>.AllocAutoRelease())
- using (var list = ListObjectPool<KeyValuePair<uint, RequestHandler>>.AllocAutoRelease())
- {
- long cur_time = CUtils.CurrentTimeMS;
- if (response_map.Count > 0)
- {
- list.AddRange(response_map);
- foreach (var req in list)
- {
- if (req.Value.CheckTimeout(request_timer.Tag, cur_time))
- {
- response_map.Remove(req.Key);
- removing.Add(req.Value);
- }
- }
- }
- else
- {
- return;
- }
- if (removing.Count > 0)
- {
- foreach (var r in removing)
- {
- PomeloException exp = new PomeloException(408, "Request Timeout : " + r.Route);
- exp.Route = r.Route;
- exp.Timeout = true;
- r.Invoke(exp);
- log.Error("socket ====== check_request_timeout exp.Route "+ exp.Route);
- }
- }
- }
- }
- }
- private void clear_response(bool async)
- {
- response_map.Clear();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- private void listen_response(uint id, string route, Action<PomeloException, object> cb, MessageDecoder dc)
- {
-
- if (id > 0 && cb != null)
- {
-
- this.response_map.Add(id, new RequestHandler(this, route, cb, null, dc));
- }
- }
- private void listen_response_binary(uint id, string route, Action<PomeloException, byte[]> cb)
- {
-
- if (id > 0 && cb != null)
- {
-
- this.response_map.Add(id, new RequestHandler(this, route, null, cb, null));
- }
- }
- protected virtual void process_response(RecvMessage msg)
- {
- RequestHandler cb;
-
- if (!response_map.TryGetValue(msg.MsgID, out cb))
- {
- log.WarnFormat("Ignore response message : {0}", msg.MsgID);
- return;
- }
- response_map.Remove(msg.MsgID);
- try
- {
-
- msg.Route = cb.Route;
- var output = msg.Stream;
- if (cb.IsBinary)
- {
- var response = msg.ReadBody();
- cb.InvokeBin(response);
- }
- else if (cb.Decoder != null)
- {
- var response = msg.ReadBody(cb.Decoder);
- if (response == null)
- {
- throw new Exception("Decode response error : " + msg.Route);
- }
- if (response is PomeloException)
- {
- cb.Invoke(response as PomeloException);
- }
- else
- {
- cb.Invoke(response);
- }
- }
- else
- {
- Type responseType = EventTypes.GetResponseType(msg.Route);
- if (responseType == null)
- {
- throw new Exception("No response type : " + msg.Route);
- }
- object response;
-
- {
- response = msg.ReadBody(this.serializer, responseType);
- }
- if (response == null)
- {
- throw new Exception("Deserialize response error : " + responseType);
- }
- else
- {
- this.addLastResponse(response);
- cb.Invoke(response);
- }
- }
- }
- catch (Exception e)
- {
- var exp = new PomeloException(501, e.Message, e);
- exp.Route = msg.Route;
- cb.Invoke(exp);
- onError(e);
- }
- }
- private PushHandler listen_push(string route, Action<object> cb, MessageDecoder dc)
- {
- var ret = new PushHandler(this, route, cb, dc);
- var act = push_handler.Get(route);
- if (act == null)
- {
- act = new List<PushHandler>();
- push_handler.Put(route, act);
- }
- act.Add(ret);
- return ret;
- }
- private void listen_push_once(string route, Action<object> cb, MessageDecoder dc)
- {
-
- {
- if (cb == null)
- {
- push_handler_once.Remove(route);
- }
- else
- {
- push_handler_once.Put(route, new PushHandler(this, route, cb, dc));
- }
- }
- }
- private PushHandler listen_push_binary(string route, Action<byte[]> cb)
- {
- var ret = new PushHandler(this, route, cb);
- var act = push_handler.Get(route);
- if (act == null)
- {
- act = new List<PushHandler>();
- push_handler.Put(route, act);
- }
- act.Add(ret);
- return ret;
- }
- private void listen_push_once_binary(string route, Action<byte[]> cb)
- {
- if (cb == null)
- {
- push_handler_once.Remove(route);
- }
- else
- {
- push_handler_once.Put(route, new PushHandler(this, route, cb));
- }
- }
- internal void remove_push(PushHandler handler)
- {
- var act = push_handler.Get(handler.Route);
- if (act != null)
- {
- act.Remove(handler);
- }
- }
- protected virtual void process_push(RecvMessage msg)
- {
- try
- {
- using (var all = ListObjectPool<PushHandler>.AllocAutoRelease())
- {
-
-
- {
- var list = push_handler.Get(msg.Route);
- if (list != null) { all.AddRange(list); }
- }
-
- {
- var once = push_handler_once.Get(msg.Route);
- if (once != null) all.Add(once);
- }
- if (all.Count > 0)
- {
- object push = null;
- byte[] push_bin = null;
- var push_type = EventTypes.GetPushType(msg.Route);
- for (int i = 0; i < all.Count; i++)
- {
- var handler = all[i];
- if (handler.IsBinary)
- {
- if (push_bin == null)
- push_bin = msg.ReadBody();
- handler.InvokeBin(push_bin);
- }
- else if (handler.decoder != null)
- {
- var decode = msg.ReadBody(handler.decoder);
- if (decode != null)
- {
- handler.Invoke(decode);
- }
- }
- else
- {
- if (push == null)
- {
- if (push_type != null)
- {
-
- {
- push = msg.ReadBody(this.serializer, push_type);
- }
- }
- }
- if (push != null)
- {
- this.addLastResponse(push);
- handler.Invoke(push);
- }
- }
- }
- }
- else
- {
- if (event_NetWorkHandlePush != null)
- {
- event_NetWorkHandlePush.Invoke(msg.Route, msg.Stream);
- }
- }
- }
- }
- catch (Exception e)
- {
- log.Error("Decode Error: route = " + msg.Route + "\n" + e.Message);
- onError(e);
- }
- }
- private void clear_push()
- {
-
- {
- push_handler.Clear();
- }
-
- {
- push_handler_once.Clear();
- }
- }
- #endregion
-
- #region LastResponse
- private bool enable_last_response = true;
- private readonly HashMap<Type, object> last_response = new HashMap<Type, object>();
- public bool IsSaveResponse
- {
- get { return enable_last_response; }
- set
- {
- enable_last_response = value;
- if (value == false)
- {
-
- {
- last_response.Clear();
- }
- }
- }
- }
- internal void addLastResponse(object push)
- {
-
- {
- if (push != null && enable_last_response)
- {
- last_response.Put(push.GetType(), push);
- }
- }
- }
- public T GetLastResponse<T>() where T : class
- {
-
- {
- return last_response.Get(typeof(T)) as T;
- }
- }
- public object GetLastResponse(Type type)
- {
-
- {
- return last_response.Get(type);
- }
- }
- public void ClearLastResponse()
- {
-
- {
- last_response.Clear();
- }
- }
- #endregion
-
- internal void onError(Exception err)
- {
- if (event_OnError != null) { event_OnError.Invoke(err); }
- }
-
- public void onRequestStart(string route, object option)
- {
- if (event_RequestStartEvent != null)
- {
- event_RequestStartEvent(route, option);
- }
- }
- public void onRequestEnd(string route, PomeloException excep, object response, object option)
- {
- if (event_RequestEndEvent != null)
- {
- event_RequestEndEvent(route, excep, response, option);
- }
- }
-
- public void Dispose()
- {
- if (this.disposed)
- return;
- this.disposing();
- this.disposing_events();
- this.disposed = true;
- }
-
-
-
-
- public event Action<NetWorkState> NetWorkStateChangedEvent
- {
- add { event_NetWorkStateChangedEvent += value; }
- remove { event_NetWorkStateChangedEvent -= value; }
- }
-
-
-
- public event ProcessMessageImmediately NetWorkHandlePushImmediately
- {
- add { event_NetWorkHandlePushImmediately += value; }
- remove { event_NetWorkHandlePushImmediately -= value; }
- }
-
-
-
- public event Action<Exception> OnError
- {
- add { event_OnError += value; }
- remove { event_OnError -= value; }
- }
-
-
-
- public event Action<string, Stream> NetWorkHandlePush
- {
- add { event_NetWorkHandlePush += value; }
- remove { event_NetWorkHandlePush -= value; }
- }
-
-
-
- public event Action<string, object> RequestStartEvent
- {
- add { event_RequestStartEvent += value; }
- remove { event_RequestStartEvent -= value; }
- }
-
-
-
- public event Action<string, PomeloException, object, object> RequestEndEvent
- {
- add { event_RequestEndEvent += value; }
- remove { event_RequestEndEvent -= value; }
- }
-
-
-
- public event Action<string> OnDisconnected
- {
- add { event_OnDisconnected += value; }
- remove { event_OnDisconnected -= value; }
- }
-
-
-
- public event Action OnHeartBeat
- {
- add { event_OnHeartBeat += value; }
- remove { event_OnHeartBeat -= value; }
- }
- private Action<Exception> event_OnError;
- private Action<string, object> event_RequestStartEvent;
- private Action<string, PomeloException, object, object> event_RequestEndEvent;
- private Action<NetWorkState> event_NetWorkStateChangedEvent;
- private Action<string> event_OnDisconnected;
- private Action<string, Stream> event_NetWorkHandlePush;
- private ProcessMessageImmediately event_NetWorkHandlePushImmediately;
- private Action event_OnHeartBeat;
- protected virtual void disposing_events()
- {
- event_OnError = null;
- event_RequestStartEvent = null;
- event_RequestEndEvent = null;
- event_NetWorkStateChangedEvent = null;
- event_OnDisconnected = null;
- event_NetWorkHandlePush = null;
- event_NetWorkHandlePushImmediately = null;
- event_OnHeartBeat = null;
- }
-
- }
- }
|