Form1.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. using HeidenhainDNCLib;
  2. using IMCS.HeidenHain;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Drawing;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Runtime.InteropServices;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using System.Windows.Forms;
  17. using HEIDENHAIN.body;
  18. using System.Net.NetworkInformation;
  19. namespace HEIDENHAIN
  20. {
  21. public partial class Form1 : Form
  22. {
  23. private int iChannel = 0;
  24. //private string RemotePath = "TNC:\\nc_prog\\ATUO";//ConfigurationManager.AppSettings["RemotePath"];
  25. private string RemotePath = "TNC:\\SMG80SKCX";//ConfigurationManager.AppSettings["RemotePath"];
  26. //连接设备列表
  27. public Dictionary<string, DNC_STATE> deviceList { get; set; } = new Dictionary<string, DNC_STATE>();
  28. private DNC_STATE m_ControlState;
  29. public Dictionary<string, JHMachineInProcess> machineList { get; set; } = new Dictionary<string, JHMachineInProcess>();
  30. //private JHMachineInProcess Machine = new JHMachineInProcess();
  31. // private JHAutomatic m_Automatic = null;
  32. // private JHFileSystem m_FileSystem = null;
  33. //private JHProcessData m_ProcessData = null;
  34. //private JHError m_Error = null;
  35. string Http_Request_Url = "http://20.20.47.107:8011/heidenhain/";
  36. bool _contine = true;//用于线程循环
  37. private AutoResetEvent autoConnectEvent = new AutoResetEvent(false);//此处需要调用System.Threading;用于触发等待的线程已发生的事件(连接)
  38. public delegate void RecvAndSendHandler(HttpListenerContext s);//此处需要调用System.Net用于请求和响应HttpListener类
  39. public event RecvAndSendHandler RecvAndSend;
  40. AsyncCallback callback;
  41. HttpListenerContext context = null;
  42. public Form1()
  43. {
  44. InitializeComponent();
  45. }
  46. private void Form1_Load(object sender, EventArgs e)
  47. {
  48. this.RecvAndSend += new RecvAndSendHandler(HttpListen_RecvAndSend);
  49. #region 添加监听的信息线程添加到线程池
  50. WaitCallback wc = new WaitCallback(http_Listen);
  51. ThreadPool.QueueUserWorkItem(wc);
  52. label1.Text = "HttpServer已开启:" + Http_Request_Url;
  53. #endregion
  54. }
  55. /// <summary>
  56. /// 监听的线程
  57. /// </summary>
  58. /// <param name="ob"></param>
  59. private void http_Listen(object ob)
  60. {
  61. callback = new AsyncCallback(acceptCallback);
  62. HttpListener httpListenner;
  63. httpListenner = new HttpListener();
  64. httpListenner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  65. httpListenner.Prefixes.Add(Http_Request_Url);
  66. httpListenner.Start();
  67. while (_contine)
  68. {
  69. try
  70. {
  71. httpListenner.BeginGetContext(callback, httpListenner);
  72. autoConnectEvent.WaitOne();
  73. }
  74. catch (Exception)
  75. {
  76. }
  77. Thread.Sleep(10);
  78. }
  79. }
  80. /// <summary>
  81. /// 回调函数
  82. /// </summary>
  83. /// <param name="ar"></param>
  84. private void acceptCallback(IAsyncResult ar)
  85. {
  86. try
  87. {
  88. context = ((HttpListener)ar.AsyncState).EndGetContext(ar);
  89. }
  90. catch (Exception)
  91. {
  92. autoConnectEvent.Set();
  93. }
  94. if (context != null)
  95. {
  96. RecvAndSend(context);//触发我们一开始声明的事件
  97. autoConnectEvent.Set();
  98. }
  99. }
  100. /// <summary>
  101. /// 接听到消息的方法
  102. /// </summary>
  103. /// <param name="cont"></param>
  104. private void HttpListen_RecvAndSend(HttpListenerContext cont)
  105. {
  106. HttpListenerRequest request = cont.Request;
  107. HttpListenerResponse response = context.Response;
  108. Servlet servlet = new MyServlet();
  109. servlet.onCreate();
  110. if (request.HttpMethod == "POST")
  111. {
  112. if (!request.Url.ToString().Contains("favicon"))
  113. {
  114. try
  115. {
  116. Stream stream = context.Request.InputStream;
  117. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  118. string body = reader.ReadToEnd();
  119. YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body);
  120. ResponseBody responseBody = new ResponseBody();
  121. RequestBody hdhBody = JsonConvert.DeserializeObject<RequestBody>(body);
  122. AddList(DateTime.Now.ToString(), "POST", hdhBody.ServerUrl + ":设备:" + hdhBody.MachineName, "OK");
  123. if (hdhBody.Type == ActionTypeEnum.Connect.ToString())
  124. {
  125. Ping pingSender = new Ping();
  126. PingReply reply = pingSender.Send(hdhBody.ServerUrl);
  127. if (reply.Status != IPStatus.Success)
  128. {
  129. responseBody.result = false;
  130. }
  131. }
  132. else
  133. {
  134. //第一次连接加入数组,以支持多台设备
  135. if (deviceList == null || (deviceList.Where(m => m.Key == hdhBody.MachineName).Count() == 0))
  136. {
  137. m_ControlState = connect(hdhBody.MachineName);
  138. //DNC连接正常,加入数组
  139. if (m_ControlState.ToString() == "DNC_STATE_MACHINE_IS_AVAILABLE")
  140. {
  141. deviceList.Add(hdhBody.MachineName, m_ControlState);
  142. }
  143. Thread.Sleep(500);
  144. }
  145. else
  146. {
  147. //取设备对应的状态
  148. m_ControlState = deviceList.Where(m => m.Key == hdhBody.MachineName).FirstOrDefault().Value;
  149. }
  150. JHMachineInProcess Machine = machineList.Where(m => m.Key == hdhBody.MachineName).FirstOrDefault().Value;
  151. if (m_ControlState != null && m_ControlState.ToString() == "DNC_STATE_MACHINE_IS_AVAILABLE")
  152. {
  153. JHError m_Error = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHERROR);
  154. JHErrorEntry2List errorsList = m_Error.GetErrorList();
  155. IJHErrorEntry2 pErrorEntry = null;
  156. for (int i = 0; i < errorsList.Count; i++)
  157. {
  158. pErrorEntry = errorsList[i];
  159. if (pErrorEntry != null && pErrorEntry.Text != null)
  160. {
  161. //Console.WriteLine("===" + pErrorEntry.Text.ToString());
  162. responseBody.errorsInfo += pErrorEntry.Text.ToString() + " ";
  163. }
  164. }
  165. if (hdhBody.Type == ActionTypeEnum.Collect.ToString())
  166. {
  167. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  168. JHProcessData m_ProcessData = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHPROCESSDATA);
  169. object pFeed = new object();
  170. object pSpeed = new object();
  171. object pRapid = new object();
  172. object proStatus = new object();
  173. //进出倍率 主轴倍率
  174. m_Automatic.GetOverrideInfo(ref pFeed, ref pSpeed, ref pRapid);
  175. m_Automatic.GetExecutionMode();
  176. DNC_STS_PROGRAM dncProgram = m_Automatic.GetProgramStatus();
  177. RunDatasInfo runDatasInfo = new RunDatasInfo();
  178. runDatasInfo.feedRate = pFeed.ToString();
  179. runDatasInfo.spindleMagnification = pSpeed.ToString();
  180. runDatasInfo.spindleSpeed = pRapid.ToString();
  181. responseBody.runDatasInfo = JsonConvert.SerializeObject(runDatasInfo);
  182. object oHours = new object();
  183. object oMinutes = new object();
  184. // --- NC uptime --------------------------------------------------------------------------
  185. m_ProcessData.GetNcUpTime(ref oHours, ref oMinutes);
  186. string ncUpTime = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString()));
  187. // --- Machine uptime ---------------------------------------------------------------------
  188. m_ProcessData.GetMachineUpTime(ref oHours, ref oMinutes);
  189. string machineUpTime = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString()));
  190. // --- Machine running time ---------------------------------------------------------------
  191. m_ProcessData.GetMachineRunningTime(ref oHours, ref oMinutes);
  192. string runningTimes = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString()));
  193. }
  194. else if (hdhBody.Type == ActionTypeEnum.Upload.ToString())
  195. {
  196. JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);
  197. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  198. string sSelectedFile = Path.GetFileName(hdhBody.Path);
  199. string dncPath = null;
  200. string tempDncPath = RemotePath + "\\2.h";
  201. if (hdhBody.Address != "")
  202. {
  203. RemotePath = RemotePath + "\\" + hdhBody.Address;
  204. }
  205. dncPath = GenPath(RemotePath, sSelectedFile);
  206. //设置临时程序为主程序
  207. m_Automatic.SelectProgram(iChannel, tempDncPath);
  208. try
  209. { //删除上传文件,try异常防止文件不存在
  210. //m_FileSystem.DeleteFile(dncPath);
  211. }
  212. catch (Exception edel)
  213. {
  214. }
  215. //上传
  216. m_FileSystem.TransmitFile(hdhBody.Path, dncPath);
  217. YG.Log.Instance.WriteLogAdd($"海德汉上传程序地址--->>{dncPath}\r\n");
  218. //设当前上传程序为主程序
  219. m_Automatic.SelectProgram(iChannel, dncPath);
  220. }
  221. else if (hdhBody.Type == ActionTypeEnum.DeleteNc.ToString())
  222. {
  223. JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);
  224. string dncPath = GenPath(RemotePath, hdhBody.Path);
  225. m_FileSystem.DeleteFile(dncPath);
  226. }
  227. else if (hdhBody.Type == ActionTypeEnum.SelectNcProgram.ToString())//选中程序
  228. {
  229. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  230. string dncPath = GenPath(RemotePath, hdhBody.Path);
  231. m_Automatic.SelectProgram(iChannel, dncPath);
  232. }
  233. else if (hdhBody.Type == ActionTypeEnum.StartNcProgram.ToString())//启动程序备用
  234. {
  235. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  236. string dncPath = GenPath(RemotePath, hdhBody.Path);
  237. YG.Log.Instance.WriteLogAdd($"海德汉执行程序地址--->>{dncPath}\r\n");
  238. m_Automatic.StartProgram(dncPath);
  239. }
  240. else if(hdhBody.Type == ActionTypeEnum.ApplyFeeding.ToString()) //申请上料功能处理
  241. {
  242. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  243. RemotePath = RemotePath + "\\" + hdhBody.Address;
  244. string dncPath = GenPath(RemotePath, hdhBody.Path);
  245. m_Automatic.SelectProgram(iChannel, dncPath);
  246. YG.Log.Instance.WriteLogAdd($"海德汉执行程序地址--->>{dncPath}\r\n");
  247. m_Automatic.StartProgram(dncPath);
  248. }
  249. else if (hdhBody.Type == ActionTypeEnum.Read.ToString())
  250. {
  251. IJHDataEntry2 DataLine = null;
  252. JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
  253. dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");
  254. string dataAccessor = @"\TABLE\"+ hdhBody.Address;
  255. IJHDataEntry2 DataTable = dataAccess.GetDataEntry2(dataAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  256. DataLine = DataTable.GetChildList()[0];
  257. String offetVal = DataLine.GetChildList()[0].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
  258. responseBody.runDatasInfo = offetVal;
  259. }
  260. else if (hdhBody.Type == ActionTypeEnum.Write.ToString())
  261. {
  262. IJHDataEntry2 DataLine = null;
  263. JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
  264. dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");
  265. string dataAccessor = @"\TABLE\" + hdhBody.Address;
  266. IJHDataEntry2 DataTable = dataAccess.GetDataEntry2(dataAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  267. DataLine = DataTable.GetChildList()[0];
  268. DataLine.GetChildList()[0].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA,hdhBody.Value, true);
  269. responseBody.result = true;
  270. }
  271. else if (hdhBody.Type == ActionTypeEnum.ToolList.ToString())
  272. {
  273. IJHDataEntry2 ToolLine = null;
  274. IJHDataEntry2List ToolCells = null;
  275. //IJHDataEntry2 ToolCell = null;
  276. List<ToolsInfo> toolsList = new List<ToolsInfo>();
  277. JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
  278. dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");
  279. //string ToolColumnNamesAccessor = @"\TABLE\TOOL\T\('1'-'50')"; // see Init()
  280. string ToolColumnNamesAccessor = @"\TABLE\TOOL_P\T\('1'-'50')";
  281. IJHDataEntry2 ToolTable = dataAccess.GetDataEntry2(ToolColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  282. IJHDataEntry2List ToolLines = ToolTable.GetChildList();
  283. int ToolLinesCount = ToolLines.Count >= 50 ? 50 : ToolLines.Count;
  284. //int ToolLinesCount = ToolLines.Count;
  285. for (int i = 0; i < ToolLinesCount; i++)
  286. {
  287. ToolLine = ToolLines[i];
  288. ToolCells = ToolLine.GetChildList();
  289. // get child list from server
  290. ToolsInfo toolsInfo = new ToolsInfo();
  291. //刀位编码
  292. int[] pCode = ToolCells[0].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
  293. toolsInfo.position = string.Join(".", pCode);
  294. toolsInfo.number = ToolCells[1].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  295. toolsInfo.name = ToolCells[2].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  296. if (!String.IsNullOrEmpty(toolsInfo.name) && !String.IsNullOrEmpty(toolsInfo.number) && pCode.Length>0 && pCode[1]>0)
  297. {
  298. string ToolNumberAccessor = @"\TABLE\TOOL\T\"+ toolsInfo.number.ToString();
  299. IJHDataEntry2List ToolList = dataAccess.GetDataEntry2(ToolNumberAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false).GetChildList();
  300. //报警期限
  301. toolsInfo.warnLife = ToolList[10].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  302. //刀具寿命目标值
  303. toolsInfo.targetLife = ToolList[11].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  304. //Cur_Time使用时间
  305. toolsInfo.curTime = ToolList[12].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  306. toolsList.Add(toolsInfo);
  307. }
  308. }
  309. //获取海德汉的刀具寿命信息
  310. responseBody.toolsInfo = JsonConvert.SerializeObject(toolsList.Distinct().ToList());
  311. }
  312. }
  313. else
  314. {
  315. responseBody.msg = m_ControlState.ToString();
  316. responseBody.result = false;
  317. deviceList.Remove(hdhBody.MachineName);
  318. }
  319. }
  320. AddList(DateTime.Now.ToString(), "POST", hdhBody.ServerUrl + ":响应数据:" + responseBody.toolsInfo, responseBody.result ? "OK" : "失败:"+ m_ControlState != null ? m_ControlState.ToString():"");
  321. response.ContentType = "application/json;charset=UTF-8";
  322. response.ContentEncoding = Encoding.UTF8;
  323. response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
  324. string retJsonData = JsonConvert.SerializeObject(responseBody);
  325. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  326. {
  327. YG.Log.Instance.WriteLogAdd($"海德汉响应结果--->>{JsonConvert.SerializeObject(JsonConvert.SerializeObject(responseBody))}--->>{body}\r\n");
  328. writer.Write(JsonConvert.SerializeObject(responseBody));
  329. writer.Close();
  330. response.Close();
  331. }
  332. }
  333. catch (Exception opcex)
  334. {
  335. YG.Log.Instance.WriteLogAdd($"海德汉响应异常--->>" + opcex.Message+"确认是否连接正常,是否自动模式,路径是否正确");
  336. AddList(DateTime.Now.ToString(), "POST", request.Url.ToString(), opcex.Message);
  337. //发生异常,清空数组,重新连接
  338. deviceList = new Dictionary<string, DNC_STATE>();
  339. }
  340. }
  341. }
  342. else if (request.HttpMethod == "GET")
  343. {
  344. if (!request.Url.ToString().Contains("favicon"))
  345. {
  346. string ip = request.QueryString["ip"];
  347. string port = request.QueryString["port"];
  348. string fun = request.QueryString["fun"];
  349. AddList(DateTime.Now.ToString(), "GET", ip + port + fun, "OK");
  350. }
  351. response.Close();
  352. }
  353. }
  354. private DNC_STATE connect(string connectName)
  355. {
  356. DNC_CNC_TYPE CncType ;
  357. IJHConnectionList connectionList = null;
  358. IJHConnection connection = null;
  359. try
  360. {
  361. JHMachineInProcess Machine = null;
  362. //第一次连接加入数组,以支持多台设备
  363. if (machineList == null || (machineList.Where(m => m.Key == connectName).Count() == 0))
  364. {
  365. Machine = new JHMachineInProcess();
  366. //DNC连接正常,加入数组
  367. machineList.Add(connectName, Machine);
  368. Thread.Sleep(20);
  369. }
  370. else
  371. {
  372. //取对应设备
  373. Machine = machineList.Where(m => m.Key == connectName).FirstOrDefault().Value;
  374. }
  375. Machine.ConnectRequest(connectName);
  376. string sCurrentMachine = Machine.currentMachine;
  377. // Find out control type
  378. connectionList = Machine.ListConnections();
  379. for (int i = 0; i < connectionList.Count; i++)
  380. {
  381. connection = connectionList[i];
  382. if (connection.name == sCurrentMachine)
  383. {
  384. CncType = connection.cncType;
  385. }
  386. if (connection != null)
  387. Marshal.ReleaseComObject(connection);
  388. }
  389. return Machine.GetState();
  390. }
  391. catch (COMException cex)
  392. {
  393. return DNC_STATE.DNC_STATE_NOT_INITIALIZED;
  394. }
  395. catch (Exception ex)
  396. {
  397. return DNC_STATE.DNC_STATE_NOT_INITIALIZED;
  398. }
  399. finally
  400. {
  401. if (connectionList != null)
  402. Marshal.ReleaseComObject(connectionList);
  403. if (connection != null)
  404. Marshal.ReleaseComObject(connection);
  405. }
  406. }
  407. private string GenPath(string part1, string part2)
  408. {
  409. string sFullPath = part1;
  410. switch (part2)
  411. {
  412. case ".":
  413. break;
  414. case "..":
  415. if (part1.EndsWith(@"\") && part1.Length > 5)
  416. part1 = part1.Substring(0, part1.Length - 3);
  417. int iLastFolderPos = part1.LastIndexOf(@"\");
  418. if (iLastFolderPos >= 0)
  419. sFullPath = part1.Substring(0, iLastFolderPos + 1);
  420. break;
  421. default:
  422. if (part1.EndsWith(@"\"))
  423. sFullPath = part1 + part2;
  424. else
  425. sFullPath = part1 + @"\" + part2;
  426. break;
  427. }
  428. return sFullPath;
  429. }
  430. public class Servlet
  431. {
  432. public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { }
  433. public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
  434. public virtual void onCreate()
  435. {
  436. }
  437. }
  438. public void AddList(string dtime, string type, string url, string res)
  439. {
  440. this.Invoke(new Action(delegate ()
  441. {
  442. listView1.BeginUpdate(); //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
  443. ListViewItem lvi = new ListViewItem();
  444. lvi.Text = dtime;
  445. lvi.SubItems.Add(type);
  446. lvi.SubItems.Add(url);
  447. lvi.SubItems.Add(res);
  448. this.listView1.Items.Insert(0, lvi);
  449. if (this.listView1.Items.Count > 100)
  450. {
  451. this.listView1.Items.Clear();
  452. }
  453. this.listView1.EndUpdate(); //结束数据处理,UI界面一次性绘制。}
  454. }));
  455. }
  456. public class MyServlet : Servlet
  457. {
  458. public override void onCreate()
  459. {
  460. base.onCreate();
  461. }
  462. public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info)
  463. {
  464. Console.WriteLine("GET:" + request.Url);
  465. byte[] buffer = Encoding.UTF8.GetBytes(info);
  466. //string sss = request.QueryString["ty"];
  467. System.IO.Stream output = response.OutputStream;
  468. output.Write(buffer, 0, buffer.Length);
  469. // You must close the output stream.
  470. output.Close();
  471. //listener.Stop();
  472. }
  473. public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
  474. {
  475. Console.WriteLine("POST:" + request.Url);
  476. byte[] res = Encoding.UTF8.GetBytes("OK");
  477. response.OutputStream.Write(res, 0, res.Length);
  478. }
  479. }
  480. }
  481. }