Form1.cs 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Data.OleDb;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Runtime.Serialization.Json;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15. using GWSocketClient.db;
  16. using GWSocketClient.model;
  17. using GWSocketClient.util;
  18. using GWSocketClient.xml;
  19. using Newtonsoft.Json;
  20. using Newtonsoft.Json.Linq;
  21. using XuanJiSocket;
  22. namespace GWSocketClient
  23. {
  24. public partial class Form1 : Form
  25. {
  26. public Form1()
  27. {
  28. InitializeComponent();
  29. }
  30. private string ip;
  31. private string port;
  32. private SocketHelper.TcpClients sockeTcpClients;
  33. private VcarecityPD vcarecityProtocolBean = null;
  34. private void Form1_Load(object sender, EventArgs e)
  35. {
  36. // XmlLoader xmlLoader = new XmlLoader();
  37. // vcarecityProtocolBean = xmlLoader.loadXml();
  38. if (vcarecityProtocolBean != null)
  39. {
  40. this.Text = vcarecityProtocolBean.ProtocolName + " - " + vcarecityProtocolBean.ProtocolNo + " - " +
  41. vcarecityProtocolBean.ProtocolStartSymbol;
  42. }
  43. SocketHelper.pushSockets = new SocketHelper.PushSockets(receiveData); //注册推送器
  44. sockeTcpClients = new SocketHelper.TcpClients();
  45. ip = tbIpaddress.Text.Trim();
  46. port = tbPort.Text.Trim();
  47. }
  48. private bool showTopForNoLoadXML()
  49. {
  50. if (vcarecityProtocolBean == null)
  51. {
  52. MessageBox.Show("请先加载XML协议文件");
  53. return false;
  54. }
  55. return true;
  56. }
  57. private void receiveData(SocketHelper.Sockets sks)
  58. {
  59. this.Invoke(new ThreadStart(delegate
  60. {
  61. if (sks.ex != null)
  62. {
  63. switch (sks.ErrorCode)
  64. {
  65. case SocketHelper.Sockets.ErrorCodes.objectNull:
  66. break;
  67. case SocketHelper.Sockets.ErrorCodes.ConnectError:
  68. break;
  69. case SocketHelper.Sockets.ErrorCodes.ConnectSuccess:
  70. addToListboxItem("状态信息:连接成功.!");
  71. break;
  72. case SocketHelper.Sockets.ErrorCodes.TrySendData:
  73. break;
  74. default:
  75. break;
  76. }
  77. addToListboxItem(string.Format("客户端信息{0}", sks.ex));
  78. }
  79. else
  80. {
  81. byte[] buffer = new byte[sks.Offset];
  82. Array.Copy(sks.RecBuffer, buffer, sks.Offset);
  83. string byteToHexStr = HexUtil.byteToHexStr(buffer);
  84. if (byteToHexStr.Equals("ServerOff"))
  85. {
  86. addToListboxItem("状态信息:服务端主动关闭!");
  87. }
  88. else
  89. {
  90. if (!byteToHexStr.Equals(""))
  91. {
  92. addToListboxItem(string.Format("收到服务端{0}发来消息:[{1}]", sks.Ip, byteToHexStr));
  93. handleResponse(sks, byteToHexStr);
  94. }
  95. else
  96. {
  97. addToListboxItem("状态信息:服务端主动关闭!");
  98. sockeTcpClients.Stop();
  99. }
  100. // listBoxShow.Text += "\r\n";
  101. // listBoxShow.Text += string.Format("服务端{0}发来消息:{1}", sks.Ip, byteToHexStr);
  102. }
  103. }
  104. }));
  105. }
  106. //处理回复信息
  107. private void handleResponse(SocketHelper.Sockets sks, string reqData)
  108. {
  109. //取出原数据功能码
  110. string functionWord = reqData.Substring(18, 2);
  111. int funcode = Utils.hexToTen(functionWord);
  112. if (!(funcode == 16 || funcode == 32))
  113. {
  114. Console.WriteLine(funcode + " 这个功能码不用回复!");
  115. return;
  116. }
  117. //16 表示要读数据,返回数据库中的数据
  118. //32 表示返回结果 成功:00 失败:01
  119. //数据长度
  120. int dataLen = Utils.hexToTen(reqData.Substring(20, 4)) * 2;
  121. string readlData = "";
  122. try
  123. {
  124. readlData = reqData.Substring(24, dataLen);
  125. }
  126. catch (Exception e)
  127. {
  128. Console.WriteLine(e.Message);
  129. addToListboxItem("数据长度与帧长度对不上!! 帧数据长度=" + (dataLen / 2) + " ,Error=" + e.Message);
  130. return;
  131. }
  132. //消息流水&测量点
  133. string flowPoint = readlData.Substring(0, 6);
  134. //ID
  135. string myId = readlData.Substring(6, 4);
  136. //对应信息
  137. string idInfo = readlData.Substring(10);
  138. //回复功能码
  139. int responceFunCode = funcode + 128;
  140. string cmd = reqData.Substring(0, 18); //前面的
  141. cmd += Utils.stringWith0(Utils.tenToHex(responceFunCode), 2); //回复功能码
  142. string body = flowPoint + myId;
  143. if (funcode == 32)
  144. {
  145. //设置数据
  146. int res = AccsessDbLoader.getInstance().setReceiveData(myId, idInfo);
  147. //成功回复00 失败回复01
  148. if (res > 0)
  149. {
  150. body += "00";
  151. AccsessDbLoader.getInstance().reloadAccessDb();
  152. }
  153. else
  154. {
  155. body += "01";
  156. }
  157. }
  158. else
  159. {
  160. //返回数据库的数据 OR 临时数据,如果临时数据有数据的话
  161. try
  162. {
  163. string responce = AccsessDbLoader.getInstance().getUserIdInfo()[myId];
  164. if (!tfTmpResponse.Text.Trim().Equals(""))
  165. {
  166. string inputRespocse = tfTmpResponse.Text.Trim();
  167. responce = Utils.stringWith0(inputRespocse, responce.Length);
  168. }
  169. body += responce;
  170. }
  171. catch (Exception e)
  172. {
  173. Console.WriteLine(e);
  174. addToListboxItem("异常,没有这个ID=(" + myId + "),ERROR=" + e.Message);
  175. return;
  176. }
  177. }
  178. cmd += Utils.stringWith0(Utils.tenToHex(body.Length / 2), 4); //长度
  179. cmd += body; //消息体
  180. cmd = Utils.calcCrcCode(cmd); //计算检验码
  181. addToListboxItem(string.Format("回复服务端{0}回应消息:[{1}]", sks.Ip, cmd));
  182. byte[] ts = HexUtil.hexToBytes(cmd);
  183. sockeTcpClients.SendData(ts);
  184. }
  185. private void tbEquipmentAddress_TextChanged(object sender, EventArgs e)
  186. {
  187. string equipmentAddress = tbEquipmentAddress.Text.Trim();
  188. tsslEquipmentAddress.Text = equipmentAddress.Length / 2.0 + "";
  189. }
  190. private void btnLogin_Click(object sender, EventArgs e)
  191. {
  192. try
  193. {
  194. /*if (!showTopForNoLoadXML())
  195. return;*/
  196. ip = tbIpaddress.Text.Trim();
  197. port = tbPort.Text.Trim();
  198. sockeTcpClients.InitSocket(ip, int.Parse(port));
  199. sockeTcpClients.Start();
  200. // string loginCmd = "7e7e7e4442832e833c8200143839383630324231313931353530343739383737f7";
  201. string loginCmd = vcarecityProtocolBean.ProtocolStartSymbol;
  202. loginCmd += tbEquipmentAddress.Text.Trim() + "82" +
  203. Utils.stringWith0(Utils.tenToHex(tbCCID.Text.Trim().Length / 2), 4);
  204. loginCmd += tbCCID.Text.Trim();
  205. loginCmd = Utils.calcCrcCode(loginCmd);
  206. //发送登录命令
  207. byte[] ts = HexUtil.hexToBytes(loginCmd);
  208. addToListboxItem(string.Format("发送到服务端:[{0}]", loginCmd));
  209. sockeTcpClients.SendData(ts);
  210. }
  211. catch (Exception ex)
  212. {
  213. // statuslist.Items.Add(string.Format("连接失败!原因:{0}", ex.Message
  214. Console.WriteLine(ex.Message);
  215. }
  216. }
  217. private void tbCCID_TextChanged(object sender, EventArgs e)
  218. {
  219. string ccid = tbCCID.Text.Trim();
  220. tsslCCIDLEN.Text = ccid.Length / 2.0 + "";
  221. }
  222. private void btnQuickLogout_Click(object sender, EventArgs e)
  223. {
  224. try
  225. {
  226. sockeTcpClients.Stop();
  227. }
  228. catch (Exception exception)
  229. {
  230. addToListboxItem("你还没有登录!!" + exception.Message);
  231. }
  232. }
  233. private void tsmiLoadXml_Click(object sender, EventArgs e)
  234. {
  235. OpenFileDialog ofd = new OpenFileDialog();
  236. ofd.Filter = "XML文件|*.xml|所有文件|*.*";
  237. if (ofd.ShowDialog() == DialogResult.OK)
  238. {
  239. string xmlFilepath = ofd.FileName;
  240. vcarecityProtocolBean = new XmlLoader().load(xmlFilepath).getVcarecityPD();
  241. }
  242. }
  243. private void btnSendData_Click(object sender, EventArgs e)
  244. {
  245. string trim = tfTmpSendData.Text.Trim();
  246. trim = trim.Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace(" ", "").Replace("-", "");
  247. if (!trim.Equals(""))
  248. {
  249. byte[] ts = HexUtil.hexToBytes(trim);
  250. addToListboxItem(string.Format("发送到服务端:[{0}]", trim));
  251. sockeTcpClients.SendData(ts);
  252. }
  253. }
  254. private void rightMenuCopyCmd_Click(object sender, EventArgs e)
  255. {
  256. int index = listBoxShow.SelectedIndex;
  257. if (index >= 0 && index < listBoxShow.Items.Count)
  258. {
  259. string info = listBoxShow.SelectedItem.ToString();
  260. if (!info.Equals(""))
  261. {
  262. if (info.Contains("[") || info.Contains("]"))
  263. {
  264. Regex reg = new Regex(@"\[\w+\]"); //注意里面的引号 要用双引号表示,而不是用反斜
  265. Match match = reg.Match(info);
  266. string ifs = match.ToString();
  267. ifs = ifs.Replace("[", "").Replace("]", "");
  268. if (!info.Equals(""))
  269. {
  270. Clipboard.SetDataObject(ifs);
  271. }
  272. else
  273. {
  274. Clipboard.SetDataObject(info);
  275. }
  276. }
  277. else
  278. {
  279. Clipboard.SetDataObject(info);
  280. }
  281. }
  282. }
  283. }
  284. private void addToListboxItem(object info)
  285. {
  286. if (listBoxShow.Items.Count > 1000)
  287. {
  288. listBoxShow.Items.Remove(0);
  289. // listBoxShow.Items.Clear();
  290. }
  291. Console.WriteLine(info);
  292. listBoxShow.Items.Add(info);
  293. listBoxShow.TopIndex = listBoxShow.Items.Count - 1;
  294. }
  295. private void rightMenuClearInfo_Click(object sender, EventArgs e)
  296. {
  297. listBoxShow.Items.Clear();
  298. }
  299. private void listBoxShow_DrawItem(object sender, DrawItemEventArgs e)
  300. {
  301. if (e.Index >= 0 && e.Index < listBoxShow.Items.Count)
  302. {
  303. e.DrawBackground();
  304. //
  305. string res = listBoxShow.Items[e.Index].ToString().ToLower();
  306. if (res.Contains("收到服务端"))
  307. {
  308. Font f = new Font("微软雅黑", e.Font.Size, FontStyle.Bold);
  309. e.Graphics.DrawString(((ListBox) sender).Items[e.Index].ToString(), f, new SolidBrush(Color.Blue),
  310. e.Bounds);
  311. }
  312. else if (res.Contains("发送到服务端") || res.Contains("回复"))
  313. {
  314. Font f = new Font("微软雅黑", e.Font.Size, FontStyle.Italic);
  315. e.Graphics.DrawString(((ListBox) sender).Items[e.Index].ToString(), f,
  316. new SolidBrush(Color.BlueViolet),
  317. e.Bounds);
  318. }
  319. else
  320. {
  321. e.Graphics.DrawString(((ListBox) sender).Items[e.Index].ToString(), e.Font,
  322. new SolidBrush(e.ForeColor),
  323. e.Bounds);
  324. }
  325. e.DrawFocusRectangle();
  326. }
  327. }
  328. /// <summary>
  329. /// 压力测试
  330. /// </summary>
  331. private void btnPressureTest_Click(object sender, EventArgs e)
  332. {
  333. ip = tbIpaddress.Text.Trim();
  334. port = tbPort.Text.Trim();
  335. int count = int.Parse(tbPresureTestCount.Text);
  336. ThreadPool.QueueUserWorkItem(o =>
  337. {
  338. for (int i = 1024; i < 1024 + count; i++)
  339. {
  340. SocketHelper.TcpClients clientx = new SocketHelper.TcpClients(); //初始化类库
  341. clientx.InitSocket(ip, int.Parse(port));
  342. clientx.Start();
  343. string loginCmd = "7e7e7e";
  344. loginCmd += "4442832e" + i;
  345. loginCmd += "820014383938363032423131393135353034373938" + i;
  346. loginCmd = Utils.calcCrcCode(loginCmd);
  347. sockeTcpClients.SendData(HexUtil.hexToBytes(loginCmd));
  348. Thread.Sleep(200);
  349. }
  350. });
  351. }
  352. private void listBoxShow_DoubleClick(object sender, EventArgs e)
  353. {
  354. int index = listBoxShow.SelectedIndex;
  355. if (index >= 0 && index < listBoxShow.Items.Count)
  356. {
  357. string info = listBoxShow.SelectedItem.ToString();
  358. if (!info.Equals(""))
  359. {
  360. if (info.Contains("[") || info.Contains("]"))
  361. {
  362. Regex reg = new Regex(@"\[\w+\]"); //注意里面的引号 要用双引号表示,而不是用反斜
  363. Match match = reg.Match(info);
  364. string ifs = match.ToString();
  365. ifs = ifs.Replace("[", "").Replace("]", "");
  366. if (!info.Equals(""))
  367. {
  368. MessageBox.Show(ifs);
  369. }
  370. }
  371. }
  372. }
  373. }
  374. private void buttonCmdManager_Click(object sender, EventArgs e)
  375. {
  376. InfoEditor ie = new InfoEditor();
  377. ie.ShowDialog();
  378. }
  379. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  380. {
  381. AccsessDbLoader.getInstance().closeConnection();
  382. }
  383. private void btnTextCmd_Click(object sender, EventArgs e)
  384. {
  385. string code = Utils.calcCrcCode("7e7e7e123456789abc20000701010107030001");
  386. // code = Utils.calcCrcCode("7e7e7e123456789abc10000501010107023f");
  387. Console.WriteLine(code);
  388. handleResponse(null, code);
  389. /*try
  390. {
  391. Dictionary<string, string> abc = AccsessDbLoader.getInstance().getUserIdInfo();
  392. MessageBox.Show(abc.Count + "");
  393. string ac = abc["0400"];
  394. MessageBox.Show(ac);
  395. }
  396. catch (Exception exception)
  397. {
  398. Console.WriteLine(exception);
  399. }*/
  400. }
  401. }
  402. }