PageRenderTime 59ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/Src/Core.TCPCommunicationClient/TCPClientBase.cs

#
C# | 196 lines | 177 code | 19 blank | 0 comment | 27 complexity | b4c4e33b3fe44ed4fc747e1b177b0ae9 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections;
  6. using System.Net;
  7. using System.IO;
  8. using Core.IO;
  9. using System.Threading;
  10. using Core.Util;
  11. using System.Reflection;
  12. using System.Net.Sockets;
  13. using System.Xml.Linq;
  14. #if !CF
  15. using Amib.Threading;
  16. using System.Xml.Linq;
  17. #endif
  18. namespace Core.TCPCommunicationClient
  19. {
  20. public abstract class TCPClientBase : EventPoint
  21. {
  22. public bool IsConnecting { get; protected set; }
  23. protected delegate void RequestAsyncDelegate(byte[] PostData);
  24. private const int listenByteBuffer = 10240;
  25. #if !CF
  26. protected static SmartThreadPool threadPool = new SmartThreadPool();
  27. #endif
  28. protected internal TCPClientBase()
  29. {
  30. }
  31. protected string HostKey { get; set; }
  32. protected IPEndPoint HostIPEndPoint { get; set; }
  33. public override void Initialization()
  34. {
  35. Connect();
  36. base.Initialization();
  37. }
  38. public void Connect()
  39. {
  40. if (_socket != null)
  41. {
  42. _socket.Close();
  43. }
  44. if (HostIPEndPoint == null)
  45. {
  46. XMLConfig xml = new XMLConfig(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Config\\TCPClientHostConfig.xml");
  47. if (xml.Exists())
  48. {
  49. try
  50. {
  51. XElement xe = xml.GetElements("Host").Where(L =>
  52. L.Attribute("Key") != null && L.Attribute("Key").Value == HostKey).FirstOrDefault();
  53. IPAddress address = IPAddress.Parse(xe.Element("HostAddress").Value);
  54. HostIPEndPoint = new IPEndPoint(address, xe.Element("HostPort").Value.ToInt());
  55. }
  56. catch (Exception ex)
  57. {
  58. AppLog.Instance.LogMessage("TCPClient XML Error \r\n" + ex.Message, AppLog.LogType.ErrorLog);
  59. return;
  60. }
  61. }
  62. else
  63. {
  64. AppLog.Instance.LogMessage("TCPClient XML does not exist ", AppLog.LogType.ErrorLog);
  65. return;
  66. }
  67. }
  68. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  69. _socket.Connect(HostIPEndPoint);
  70. IsConnecting = true;
  71. if (ConnectEvent != null)
  72. ConnectEvent(this, EventArgs.Empty);
  73. #if !CF
  74. TCPClientFactory.ThreadPool.QueueWorkItem(new WorkItemCallback(listen));
  75. #else
  76. Thread listenThread = new Thread(new ThreadStart(listen));
  77. listenThread.IsBackground = true;
  78. listenThread.Start();
  79. #endif
  80. }
  81. public void Disconnect()
  82. {
  83. if (_socket != null)
  84. {
  85. IsConnecting = false;
  86. _socket.Shutdown(SocketShutdown.Both);
  87. _socket.Close();
  88. if (DisconnectEvent != null)
  89. DisconnectEvent(this, EventArgs.Empty);
  90. }
  91. }
  92. private Socket _socket = null;
  93. protected Socket clientSocket
  94. {
  95. get
  96. {
  97. if (_socket == null)
  98. {
  99. Connect();
  100. }
  101. return _socket;
  102. }
  103. }
  104. private object listen(object o)
  105. {
  106. listen();
  107. return null;
  108. }
  109. private void listen()
  110. {
  111. while (clientSocket.Connected)
  112. {
  113. try
  114. {
  115. byte[] data = new byte[listenByteBuffer];
  116. int recv = clientSocket.Receive(data);
  117. if (recv == 0)
  118. {
  119. IsConnecting = false;
  120. clientSocket.Close();
  121. return;
  122. }
  123. processPostBackData(data, recv);
  124. }
  125. catch
  126. {
  127. IsConnecting = false;
  128. if (DisconnectEvent != null)
  129. DisconnectEvent(this, EventArgs.Empty);
  130. return;
  131. }
  132. }
  133. }
  134. public event GeneralEventHandler<byte[]> DataPostBackEvent;
  135. protected virtual void processPostBackData(byte[] data, int recv)
  136. {
  137. if (DataPostBackEvent != null)
  138. DataPostBackEvent(this, data);
  139. }
  140. private void _request(object o)
  141. {
  142. if (o is byte[])
  143. {
  144. Request((byte[])o);
  145. }
  146. }
  147. public void Request(byte[] PostData)
  148. {
  149. if (IsConnecting && clientSocket.Connected)
  150. {
  151. try
  152. {
  153. clientSocket.Send(PostData);
  154. }
  155. catch (Exception ex)
  156. {
  157. Disconnect();
  158. AppLog.Instance.LogMessage("TCPClient error : \r\n" + ex.Message, AppLog.LogType.WarningLog);
  159. }
  160. }
  161. }
  162. public void RequestAsync(byte[] PostData)
  163. {
  164. if (IsConnecting)
  165. {
  166. #if !CF
  167. RequestAsyncDelegate ra = new RequestAsyncDelegate(RequestAsync);
  168. ra.BeginInvoke(PostData, null, null);
  169. #else
  170. ThreadPool.QueueUserWorkItem(new WaitCallback(_request), PostData);
  171. #endif
  172. }
  173. }
  174. public event EventHandler ConnectEvent;
  175. public event EventHandler DisconnectEvent;
  176. }
  177. }