Form1.cs 18KB

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