QuotationTcpLinkProxy.cs 9.9 KB

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