QuotationTcpLinkProxy.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Muchinfo.Communication;
  6. namespace Muchinfo.MTPClient.Infrastructure.LinkProxy.TCP
  7. {
  8. public class QuotationTcpLinkProxy
  9. {
  10. private TcpPoint _client;
  11. private readonly object syncRoot = new object();
  12. private IDatagramResolver _resolver;
  13. private readonly string _address;
  14. private readonly int _port;
  15. private bool _isOnLine = false;
  16. private const int c_timeOutSencond = 30; //异步超时时间
  17. private Task timeOutTask;
  18. private readonly int _heartbeatInterval = 6;
  19. public event EventHandler<DatagramEventArgs> DatagramRecieved;
  20. public event EventHandler<CommunicationStateEventArgs> StateChanged;
  21. private uint _sessionid = 0;
  22. private static object _lockSessionid = new object();
  23. private readonly Dictionary<uint, Action<Datagram, IDatagramResolver>> requestDictionary =
  24. new Dictionary<uint, Action<Datagram, IDatagramResolver>>(); //回调字典
  25. private readonly Dictionary<uint, int> timeOutSencondDic = new Dictionary<uint, int>(); //会话ID 超时时间
  26. private readonly Dictionary<uint, AsyncResult<Datagram>> asyncDictionary = new Dictionary<uint, AsyncResult<Datagram>>();
  27. //回调字典
  28. /// <summary>
  29. /// 创建Tcp代理,打开时会阻塞
  30. /// </summary>
  31. /// <param name="host">The host.</param>
  32. /// <param name="port">The port.</param>
  33. /// <param name="heartbeatInterval">心跳时间</param>
  34. public QuotationTcpLinkProxy(string host, int port, int heartbeatInterval = 6)
  35. {
  36. _address = host;
  37. _port = port;
  38. _heartbeatInterval = heartbeatInterval;
  39. Open();
  40. }
  41. /// <summary>
  42. /// 打开连接
  43. /// </summary>
  44. public void Open()
  45. {
  46. this.Close(); //先关闭之前的连接
  47. InitializeClient();
  48. }
  49. /// <summary>
  50. /// 关闭当前连接
  51. /// </summary>
  52. public void Close()
  53. {
  54. if (this._client != null)
  55. {
  56. this._client.StateChanged -= this.Client_StateChanged;
  57. this._client.DatagramReceived -= this.Client_DatagramRecieved;
  58. this.Dispose();
  59. this._client = null;
  60. this.Enabled = false;
  61. requestDictionary.Clear();
  62. if (timeOutTask != null)
  63. {
  64. timeOutTask.Dispose();
  65. }
  66. }
  67. }
  68. public uint SessionId
  69. {
  70. get
  71. {
  72. lock (_lockSessionid)
  73. {
  74. do
  75. {
  76. if (_sessionid == uint.MaxValue)
  77. {
  78. _sessionid = 0;
  79. }
  80. ++_sessionid;
  81. } while (requestDictionary.ContainsKey(_sessionid));
  82. return _sessionid;
  83. }
  84. }
  85. }
  86. private bool _isInit;
  87. /// <summary>
  88. /// 行情连接是否初始化完成
  89. /// </summary>
  90. public bool IsInit
  91. {
  92. get
  93. {
  94. return _isInit;
  95. }
  96. }
  97. private void CheckTimeOutService()
  98. {
  99. _isInit = true;
  100. while (true)
  101. {
  102. Thread.Sleep(1000);
  103. var keys = new List<uint>(timeOutSencondDic.Keys);
  104. foreach (var key in keys)
  105. {
  106. if (timeOutSencondDic[key] <= 0)
  107. {
  108. timeOutSencondDic.Remove(key);
  109. if (requestDictionary.ContainsKey(key)) //处理超时
  110. {
  111. requestDictionary.Remove(key);
  112. }
  113. else if (asyncDictionary.ContainsKey(key))
  114. {
  115. asyncDictionary[key].SetTimeOut();
  116. asyncDictionary.Remove(key);
  117. }
  118. }
  119. else
  120. {
  121. timeOutSencondDic[key] -= 1;
  122. }
  123. }
  124. }
  125. }
  126. /// <summary>
  127. /// 回调的方法请求行情数据
  128. /// </summary>
  129. /// <param name="asyncCallAction">回调的方法</param>
  130. /// <param name="param">参数</param>
  131. /// <returns>返回0表示发送</returns>
  132. public uint AsyncSend(Action<Datagram, IDatagramResolver> asyncCallAction, Datagram param)
  133. {
  134. uint id = SessionId;
  135. requestDictionary[id] = asyncCallAction;
  136. timeOutSencondDic[id] = c_timeOutSencond;
  137. param.SessionId = id;
  138. try
  139. {
  140. if (this._client != null)
  141. {
  142. this._client.AsyncSend(param);
  143. return id;
  144. }
  145. }
  146. catch
  147. {
  148. requestDictionary.Remove(id);
  149. timeOutSencondDic.Remove(id);
  150. //todo:状态栏显示失败原因
  151. }
  152. return 0; ////发送失败
  153. }
  154. public uint AsyncSend(AsyncResult<Datagram> asyncResult, Datagram param)
  155. {
  156. uint id = SessionId;
  157. if (!IsInit) ////服务未初始化完成不进行服务调用.
  158. {
  159. asyncResult.SetTimeOut();
  160. return id;
  161. }
  162. asyncDictionary[id] = asyncResult;
  163. timeOutSencondDic[id] = c_timeOutSencond;
  164. param.SessionId = id;
  165. try
  166. {
  167. if (this._client != null)
  168. {
  169. this._client.AsyncSend(param);
  170. return id;
  171. }
  172. }
  173. catch
  174. {
  175. asyncDictionary.Remove(id);
  176. timeOutSencondDic.Remove(id);
  177. //todo:状态栏显示失败原因
  178. }
  179. return 0; ////发送失败
  180. }
  181. private void InitializeClient()
  182. {
  183. lock (this.syncRoot)
  184. {
  185. try
  186. {
  187. if (this._client == null)
  188. {
  189. this._client = new TcpPoint(_address, _port);
  190. if (this._resolver != null)
  191. {
  192. this._client.Resolver = this._resolver;
  193. }
  194. this._client.StateChanged += this.Client_StateChanged;
  195. this._client.DatagramReceived += this.Client_DatagramRecieved;
  196. this._client.HeartbeatInterval = _heartbeatInterval;
  197. this._client.HeartbeatEnabled = true;
  198. this._client.Open();
  199. this.Enabled = true;
  200. timeOutTask = Task.Factory.StartNew(() => CheckTimeOutService());
  201. }
  202. }
  203. catch (Exception ex)
  204. {
  205. if (this._client != null)
  206. {
  207. this.Client_StateChanged(this,
  208. new CommunicationStateEventArgs(this._client.SessionId, CommunicationState.Closed));
  209. }
  210. this.Close();
  211. }
  212. }
  213. }
  214. public bool Enabled
  215. {
  216. get;
  217. private set;
  218. }
  219. /// <summary>
  220. /// 异步等时间
  221. /// </summary>
  222. public int AsycnTimeOutSencond
  223. {
  224. get { return c_timeOutSencond; }
  225. }
  226. public IDatagramResolver Resolver
  227. {
  228. get
  229. {
  230. if (this._client != null)
  231. {
  232. return this._client.Resolver;
  233. }
  234. return null;
  235. }
  236. }
  237. /// <summary>
  238. /// Sends the specified datagram.
  239. /// </summary>
  240. /// <param name="datagram">The datagram.</param>
  241. public void Send(Datagram datagram)
  242. {
  243. try
  244. {
  245. if (this._client != null)
  246. {
  247. this._client.AsyncSend(datagram);
  248. }
  249. }
  250. catch (Exception ex)
  251. {
  252. }
  253. }
  254. private void Client_StateChanged(object sender, CommunicationStateEventArgs e)
  255. {
  256. if (StateChanged != null)
  257. {
  258. StateChanged(this, e);
  259. _isOnLine = e.State == CommunicationState.Opened;
  260. }
  261. }
  262. private void Client_DatagramRecieved(object sender, DatagramEventArgs e)
  263. {
  264. var sessionid = e.Datagram.SessionId;
  265. if (requestDictionary.ContainsKey(sessionid))
  266. {
  267. Task.Factory.StartNew(() =>
  268. {
  269. try
  270. {
  271. //回调函数中处理异常
  272. requestDictionary[sessionid].Invoke(e.Datagram, this.Resolver);
  273. }
  274. finally
  275. {
  276. requestDictionary.Remove(sessionid);
  277. if (timeOutSencondDic.ContainsKey(sessionid))
  278. {
  279. timeOutSencondDic.Remove(sessionid);
  280. }
  281. }
  282. });
  283. }
  284. else if (asyncDictionary.ContainsKey(sessionid))
  285. {
  286. asyncDictionary[sessionid].Complete(e.Datagram, DateTime.Now);
  287. }
  288. if (DatagramRecieved != null)
  289. {
  290. DatagramRecieved(this, e);
  291. }
  292. }
  293. public void Dispose()
  294. {
  295. lock (this.syncRoot)
  296. {
  297. if (this._client != null)
  298. {
  299. if (this._client.State != CommunicationState.Closing && this._client.State != CommunicationState.Closed)
  300. {
  301. this._client.Close();
  302. }
  303. else
  304. {
  305. this._client.Dispose();
  306. }
  307. this._client = null;
  308. }
  309. }
  310. }
  311. }
  312. }