SocketClient.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Timers;
  10. using System.Windows.Forms;
  11. using Timer = System.Timers.Timer;
  12. namespace Core.StlMes.Client.LgResMgt.Mcms
  13. {
  14. public class SocketClient : iCommunication
  15. {
  16. private Socket _socketClient;
  17. private Task sendTask;
  18. private readonly Timer timer = new Timer();
  19. public SocketClient()
  20. {
  21. timer.Elapsed += timer_Elapsed;
  22. timer.Interval = 1 * 5 * 1000;
  23. }
  24. private void timer_Elapsed(object sender, ElapsedEventArgs e)//判断是否连接成功
  25. {
  26. if(_socketClient==null) return;
  27. if (Reconnecting) return;
  28. if (Status && !Reconnect)
  29. {
  30. if (_socketClient.Connected)
  31. {
  32. try
  33. {
  34. byte[] temp = new byte[1]{0x00};
  35. // _socketClient.Send(temp, 0, 0);
  36. Reconnect = false;
  37. }
  38. catch (SocketException ex)
  39. {
  40. if (ex.NativeErrorCode.Equals(10035)) //仍然是connect的
  41. Reconnect = false;
  42. else
  43. Reconnect = true;
  44. }
  45. Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  46. try
  47. {
  48. test.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
  49. }
  50. catch (SocketException ex)
  51. {
  52. if (ex.NativeErrorCode.Equals(10035)) //仍然是connect的
  53. Reconnect = false;
  54. else
  55. Reconnect = true;
  56. }
  57. finally
  58. {
  59. test.Disconnect(false);
  60. test.Shutdown(SocketShutdown.Both);
  61. test.Close();
  62. }
  63. }
  64. else
  65. {
  66. Reconnect = true;
  67. }
  68. }
  69. //连接已经断开
  70. if (Reconnect)
  71. {
  72. Reconnecting = true;
  73. OnReceiveDataA("0", "服务器断开,重量清0!", DataType.ReceiveData);
  74. OnReceiveDataA("0", "服务器断开,重新连接!", DataType.ClientReconnect);
  75. if (Status)
  76. {
  77. try
  78. {
  79. if (_socketClient != null)
  80. {
  81. _socketClient.Shutdown(SocketShutdown.Both);
  82. _socketClient.Close();
  83. _status = false;
  84. }
  85. }
  86. catch (Exception)
  87. {
  88. }
  89. }
  90. try
  91. {
  92. _socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  93. //连接服务器
  94. _socketClient.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
  95. //请求获取数据
  96. _socketClient.Send(new byte[] { 0xE6, 0X00, 0XE7 });
  97. byte[] buffer = new byte[2048];
  98. _socketClient.ReceiveTimeout = 5000;
  99. int count = _socketClient.Receive(buffer);
  100. if (count <= 0 || !(buffer[0] == 0xE6 && buffer[1] == 0x00 && buffer[2] == 0xE7))
  101. {
  102. return;
  103. }
  104. _status = true;
  105. Reconnect = false;
  106. sendTask = new Task(() => StartReceive());
  107. sendTask.Start();
  108. OnReceiveDataA("", string.Format("开启监听 ip:{0} 端口:{1} ", Ip, Port), DataType.Open);
  109. }
  110. catch (Exception)
  111. {
  112. }
  113. Reconnecting = false;
  114. }
  115. }
  116. public void Start()
  117. {
  118. try
  119. {
  120. //实例化socket
  121. _socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  122. //连接服务器
  123. _socketClient.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
  124. //请求获取数据
  125. // _socketClient.Send(new byte[] { 0xE6, 0X00, 0XE7 });---
  126. // byte[] buffer = new byte[2048];--
  127. // _socketClient.ReceiveTimeout = 5000;--
  128. // int count = _socketClient.Receive(buffer);--
  129. /*
  130. if (count <= 0 || !(buffer[0] == 0xE6 && buffer[1] == 0x00 && buffer[2] == 0xE7))
  131. {
  132. MessageBox.Show("请求远程服务器失败!");
  133. return;
  134. }*/
  135. // timer.Start();
  136. _status = true;
  137. Reconnect = false;
  138. _socketClient.Blocking = true;
  139. sendTask = new Task(() => StartReceive());
  140. sendTask.Start();
  141. //OnReceiveDataA("", string.Format("开启监听 ip:{0} 端口:{1} ", Ip, Port), DataType.Open);
  142. }
  143. catch (Exception ex)
  144. {
  145. OnReceiveData(null, ex.Message, DataType.Error);
  146. }
  147. }
  148. /// <summary>
  149. /// 采用Socket方式,测试服务器连接
  150. /// </summary>
  151. /// <param name="host">服务器主机名或IP</param>
  152. /// <param name="port">端口号</param>
  153. /// <param name="millisecondsTimeout">等待时间:毫秒</param>
  154. /// <returns></returns>
  155. public static bool TestConnection(string host, int port)
  156. {
  157. int millisecondsTimeout = 5;//等待时间
  158. TcpClient client = new TcpClient();
  159. try
  160. {
  161. var ar = client.BeginConnect(host, port, null, null);
  162. ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
  163. return client.Connected;
  164. }
  165. catch (Exception e)
  166. {
  167. throw e;
  168. }
  169. finally
  170. {
  171. client.Close();
  172. }
  173. }
  174. public void Stop()
  175. {
  176. try
  177. {
  178. if (_socketClient != null)
  179. {
  180. _socketClient.Shutdown(SocketShutdown.Both);
  181. _socketClient.Close();
  182. }
  183. }
  184. catch (Exception)
  185. {
  186. }
  187. _status = false;
  188. Reconnect = false;
  189. timer.Stop();
  190. // OnReceiveDataA("", "断开与服务器的连接 ", DataType.Close);
  191. }
  192. /// <summary>
  193. /// 开启接收
  194. /// </summary>
  195. /// <param name="obj"></param>
  196. private void StartReceive()
  197. {
  198. var ReceiveData = new List<byte>();
  199. while (Status && !Reconnect)//
  200. {
  201. try
  202. {
  203. byte[] buffer = new byte[2048];
  204. int count = _socketClient.Receive(buffer);
  205. if (count > 0)
  206. {
  207. var Datas = buffer.ToList().Take(count);
  208. ReceiveData = ReceiveData.Concat(Datas).ToList();
  209. object Data;
  210. DeframeType Result = DeframeType.UnKnow;
  211. while (ReceiveData.Any() && Result != DeframeType.LengthLess)
  212. {
  213. List<Byte> rightData;
  214. Result = _protocol.AnalaysData(ReceiveData, out Data, out rightData);
  215. if (Result != DeframeType.RightFrame && Result != DeframeType.LengthLess) ReceiveData.Clear();
  216. if (Result == DeframeType.RightFrame)
  217. {
  218. OnReceiveData(Data, "成功解析数据!" + Data.ToString(), DataType.ReceiveData, rightData.ToArray());
  219. }
  220. if (Result == DeframeType.WrongFrame)
  221. {
  222. OnReceiveData(null, "数据解析失败", DataType.EvenMessage);
  223. }
  224. }
  225. }
  226. }
  227. catch (Exception ex)
  228. {
  229. // MessageBox.Show(ex.ToString());
  230. }
  231. }
  232. }
  233. public event ReceiveDataHandler ReceiveData;
  234. private IProtocol _protocol;
  235. public void ChangeProtocol(IProtocol iProtocol)
  236. {
  237. _protocol = iProtocol;
  238. }
  239. private bool _status;
  240. public bool Status {
  241. get { return _status || Reconnect; }
  242. }
  243. public bool Reconnect { get;private set; }
  244. public bool Reconnecting { get; private set; }
  245. protected virtual void OnReceiveData(object data, string message, DataType dataType, byte[] bData = null)
  246. {
  247. var handler = ReceiveData;
  248. if (handler != null)
  249. new Task(() => { handler(this, data, message, dataType, bData);
  250. if (dataType == DataType.ReceiveData)
  251. {
  252. double wt;
  253. if (double.TryParse(data.ToString2(), out wt))
  254. {
  255. WeightValue = (wt / 100d).ToString("0.00") + "t";
  256. };
  257. }
  258. }).Start();
  259. // handler(this, data, DeviceName + " " + message);
  260. }
  261. protected virtual void OnReceiveDataA(object data, string message, DataType dataType, byte[] bData = null)
  262. {
  263. var handler = ReceiveData;
  264. if (handler != null)
  265. handler(this, data, message, dataType, bData);
  266. // handler(this, data, DeviceName + " " + message);
  267. }
  268. public string Ip { get; set; }
  269. // public string SportNo { get; set; } //点位信息
  270. public bool Show { get; set; }//是否显示
  271. public string Port { get; set; }
  272. public string WeightValue { get; set; }//重量信息
  273. public override string ToString()
  274. {
  275. return "远程服务器[" + Ip + ":" + Port + "] ";
  276. }
  277. }
  278. }