TCPClient.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 Toolkit.Log4;
  10. using static Toolkit.Tcp.TCPServer;
  11. namespace Toolkit.Tcp
  12. {
  13. public class TCPClient
  14. {
  15. /// <summary>
  16. /// 所有可以正常使用的连接
  17. /// </summary>
  18. public static List<TCPClient> sockets = new List<TCPClient>();
  19. public List<IPEndPoint> endps = new List<IPEndPoint>();
  20. public static bool createState = true;//创建是否成功
  21. public Socket socket;
  22. public string startstr;
  23. public string stopstr;
  24. public IPEndPoint iPEndPoint= new IPEndPoint(IPAddress.Parse("192.168.2.99"), 8888);//192.168.2.99
  25. public TCPClient()
  26. {
  27. Connect();
  28. }
  29. public void Connect()
  30. {
  31. try
  32. {
  33. AddressFamily addressFamily = AddressFamily.InterNetwork;
  34. SocketType socketType = SocketType.Stream;
  35. ProtocolType protocolType = ProtocolType.Tcp;
  36. socket = new Socket(addressFamily, socketType, protocolType);
  37. socket.Connect(iPEndPoint);
  38. LogHelper.Info(iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port + " 已连接");
  39. socket.ReceiveTimeout = 2000;
  40. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
  41. // 配置Keep-Alive参数(空闲3秒,间隔1秒,尝试3次)
  42. byte[] keepAliveParams = new byte[] {
  43. 1, 0, 0, 0, // 启用Keep-Alive
  44. 0x88, 0x13, 0, 0, // 空闲时间3000ms (十六进制0x00001388)
  45. 0xE8, 0x03, 0, 0, // 探测间隔1000ms (0x000003E8)
  46. 3, 0, 0, 0 // 探测次数3次
  47. };
  48. socket.IOControl(IOControlCode.KeepAliveValues, keepAliveParams, null);
  49. // 参数说明:空闲60秒后探测,间隔5秒,尝试3次 ‌:ml-citation{ref="5,8" data="citationList"}
  50. // startstr = tcp.StartStr;
  51. //stopstr = tcp.StopStr;
  52. sockets.Add(this);
  53. createState = true;
  54. string str = ReceiveVarData(socket);
  55. LogHelper.Info(str);
  56. }
  57. catch
  58. {
  59. createState = false;
  60. if ( socket.Connected )
  61. {
  62. socket.Close();
  63. }
  64. }
  65. }
  66. public string SendAndReceive(string msg, int timeout = 2000)
  67. {
  68. try
  69. {
  70. byte[] msgbytes = Encoding.Default.GetBytes(msg);
  71. int i = socket.Send(msgbytes);
  72. byte[] bytes = new byte[256];
  73. i = socket.Receive(bytes);
  74. if ( i != 0 )
  75. {
  76. string str = Encoding.Default.GetString(bytes);
  77. str = str.Substring(0, i);
  78. int startindex = 0;
  79. int stopindex = 0;
  80. //if (startstr.Length != 0 && stopstr.Length != 0)
  81. //{
  82. // startindex = str.IndexOf(startstr);
  83. // stopindex = str.IndexOf(stopstr);
  84. //}
  85. //if (startindex != -1 && stopindex != -1)
  86. {
  87. // str = str.Substring(startindex + startstr.Length, stopindex - (startindex + startstr.Length));
  88. if ( str.Length != 0 )
  89. {
  90. LogHelper.Info("-" + socket.RemoteEndPoint.ToString() + ":" + str + "\r\n");
  91. return str;
  92. }
  93. else
  94. {
  95. return "ERROR";
  96. }
  97. }
  98. }
  99. return null;
  100. }
  101. catch ( Exception ex )
  102. {
  103. LogHelper.error.Error("", ex);
  104. return "";
  105. }
  106. }
  107. public string SendLinux(string NowSendData, int printcount = 1, int autostop = 0, int encode = 1)
  108. {
  109. string sends = "";
  110. byte[] endbyte = new byte[] { 00, 00, 03, 04 };
  111. if ( NowSendData != "" )
  112. {
  113. byte[] VerBin = new byte[10000];
  114. //计算校验字节。
  115. byte VerByte = 0;
  116. List<byte> CRCBuffer = new List<byte>();
  117. CRCBuffer.Add(0x1D); //起始
  118. CRCBuffer.Add(( byte ) ( printcount & 0xff ));
  119. CRCBuffer.Add(( byte ) ( ( printcount & 0xff00 ) >> 8 ));
  120. CRCBuffer.Add(( byte ) ( ( printcount & 0xff0000 ) >> 16 ));
  121. CRCBuffer.Add(( byte ) ( ( printcount & 0xff000000 ) >> 24 ));
  122. if ( autostop == 0 )
  123. CRCBuffer.Add(0x0A);
  124. else
  125. CRCBuffer.Add(0x0B);
  126. encode = 1; //220904统一采用utf8格式发送,解决部分gb2312乱码(二维码中)
  127. switch ( encode )
  128. {
  129. case 0:
  130. VerBin = System.Text.Encoding.GetEncoding("gb2312").GetBytes(NowSendData);
  131. CRCBuffer.Add(0xC1);
  132. break;
  133. case 1:
  134. VerBin = System.Text.Encoding.UTF8.GetBytes(NowSendData);
  135. CRCBuffer.Add(0xC2);
  136. break;
  137. case 2:
  138. VerBin = System.Text.Encoding.Unicode.GetBytes(NowSendData);
  139. CRCBuffer.Add(0xC3);
  140. break;
  141. }
  142. CRCBuffer.AddRange(VerBin); //数据
  143. VerByte = CRC8(CRCBuffer.ToArray());
  144. CRCBuffer.Add(VerByte);
  145. CRCBuffer.AddRange(endbyte);
  146. byte[] sendbuff = CRCBuffer.ToArray();
  147. LogHelper.Info(" 发送给打印机: outdata");
  148. string res = SendVarData(socket, Encoding.UTF8.GetBytes("outdata"));
  149. LogHelper.Info(" 打印机返回: " + res);
  150. if ( res != "Fail" && res != "Err" )
  151. {
  152. LogHelper.Info(" 发送给打印机: " + NowSendData);
  153. res = SendVarData(socket, sendbuff);
  154. LogHelper.Info(" 打印机返回: " + res);
  155. }
  156. return res;
  157. }
  158. else
  159. {
  160. return "null";
  161. }
  162. }
  163. public string ReceiveVarData(Socket s)
  164. {
  165. int total = 0;
  166. int recv;
  167. string datas = "";
  168. if ( s == null )
  169. return "未连接";
  170. if ( !s.Connected )
  171. {
  172. return "未连接";
  173. }
  174. int size = 0;
  175. byte[] datasize = new byte[4];
  176. try
  177. {
  178. recv = s.Receive(datasize, 0, 4, SocketFlags.None);
  179. }
  180. catch
  181. {
  182. return "未收到数据";
  183. }
  184. size = BitConverter.ToInt32(datasize, 0);
  185. if ( size == 0 )
  186. return "未收到数据";
  187. for ( int i = 0; i < datasize.Length; i++ )
  188. datas += datasize[ i ].ToString("X2") + " ";
  189. int dataleft = size;
  190. byte[] data = new byte[size];
  191. while ( total < size )
  192. {
  193. recv = s.Receive(data, total, dataleft, SocketFlags.None);
  194. if ( recv == 0 )
  195. {
  196. data = null;
  197. break;
  198. }
  199. total += recv;
  200. dataleft -= recv;
  201. }
  202. datas = "";
  203. return Encoding.UTF8.GetString(data);
  204. }
  205. public static byte CRC8(byte[] buffer)
  206. {
  207. byte crc = 0;
  208. for ( int j = 0; j < buffer.Length; j++ )
  209. {
  210. crc ^= buffer[ j ];
  211. for ( int i = 0; i < 8; i++ )
  212. {
  213. if ( ( crc & 0x01 ) != 0 )
  214. {
  215. crc >>= 1;
  216. crc ^= 0x8c;
  217. }
  218. else
  219. {
  220. crc >>= 1;
  221. }
  222. }
  223. }
  224. return crc;
  225. }
  226. public string SendVarData(Socket s, byte[] data)
  227. {
  228. if ( s == null )
  229. return "null";
  230. if ( !s.Connected )
  231. {
  232. return "未连接";
  233. }
  234. string datas = "";
  235. try
  236. {
  237. int total = 0;
  238. int size = data.Length;
  239. int dataleft = size;
  240. int sent;
  241. byte[] datasize = new byte[4];
  242. datasize = BitConverter.GetBytes(size);
  243. sent = s.Send(datasize);
  244. datas = "";
  245. while ( total < size )
  246. {
  247. sent = s.Send(data, total, dataleft, SocketFlags.None);
  248. total += sent;
  249. dataleft -= sent;
  250. }
  251. if ( total != 0 )
  252. {
  253. return "OK";
  254. }
  255. return "Fail";
  256. }
  257. catch ( Exception ex )
  258. {
  259. return "Err";
  260. }
  261. }
  262. public int Send(string msg, int timeout = 2000)
  263. {
  264. try
  265. {
  266. byte[] msgbytes = Encoding.Default.GetBytes(msg);
  267. int i = socket.Send(msgbytes);
  268. LogHelper.Info("本地发送数据:" + msg);
  269. return i;
  270. }
  271. catch ( Exception ex )
  272. {
  273. LogHelper.error.Error("", ex);
  274. return -1;
  275. }
  276. }
  277. public string Receive(int timeout = 2000)
  278. {
  279. try
  280. {
  281. byte[] bytes = new byte[256];
  282. int i = socket.Receive(bytes);
  283. if ( i != 0 )
  284. {
  285. return null;
  286. }
  287. return null;
  288. }
  289. catch ( Exception ex )
  290. {
  291. LogHelper.error.Error("", ex);
  292. return null;
  293. }
  294. }
  295. }
  296. }