CentralForWebSocketServer.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using parkMonitor.entity;
  7. using System.Configuration;
  8. using System.Net.Sockets;
  9. using System.Net;
  10. using System.Threading;
  11. using parkMonitor.tools;
  12. using parkMonitor.LOG;
  13. using MySql.Data.MySqlClient;
  14. namespace centralController.WebServer
  15. {
  16. /// <summary>
  17. /// web线程类,接收用户指令
  18. /// </summary>
  19. public class CentralForWeb : IWebServer
  20. {
  21. public MultiSocketThread multiSocketThread { set; get; }
  22. public static BlockingQueue blockingQueue = new BlockingQueue();
  23. private Queue<MessageUTF8> reserveQueue = null;
  24. private object reserveLock = new object();
  25. Int32 port;
  26. IPAddress localAddr;
  27. bool isClosing;
  28. //public AbstractMessage GetMessage()
  29. //{
  30. // return (AbstractMessage)blockingQueue.Dequeue();
  31. //}
  32. private void WebConnect(TcpListener listener)
  33. {
  34. try
  35. {
  36. if (listener != null)
  37. {
  38. //得到包含客户端信息的套接字
  39. var tcpClient = listener.AcceptTcpClient();
  40. //创建消息服务线程对象
  41. //把multiSocket类的run方法委托给线程
  42. multiSocketThread = new MultiSocketThread(tcpClient);
  43. Thread newThread = new Thread(multiSocketThread.Run);
  44. newThread.IsBackground = true;
  45. newThread.Start();
  46. }
  47. }
  48. catch (Exception e)
  49. {
  50. if (multiSocketThread != null)
  51. multiSocketThread.Close();
  52. Console.WriteLine(e.Message);
  53. throw new Exception();
  54. }
  55. }
  56. private void Run()
  57. {
  58. bool linked = false;
  59. //web重连机制
  60. Task.Factory.StartNew(() =>
  61. {
  62. TcpListener listener = null;
  63. try
  64. {
  65. listener = LazySingleton.GetInstance(localAddr, port);
  66. listener.Start();
  67. linked = true;
  68. }
  69. catch (Exception) { Console.WriteLine("未能与Web服务器连接,本地ip错误或网络异常"); linked = false; }
  70. while (isClosing)
  71. {
  72. try
  73. {
  74. while (linked)
  75. {
  76. WebConnect(listener);
  77. }
  78. if (!linked)
  79. {
  80. throw new Exception();
  81. }
  82. }
  83. catch (Exception)
  84. {
  85. //Task.Factory.StartNew(() =>
  86. //{
  87. MyTimer mt = new MyTimer();
  88. mt.StartTiming();
  89. while (!linked)
  90. {
  91. Thread.Sleep(10000);
  92. try
  93. {
  94. listener = LazySingleton.GetInstance(localAddr, port);
  95. listener.Start();
  96. linked = true;
  97. Console.WriteLine("web已成功重连");
  98. break;
  99. }
  100. catch (Exception)
  101. {
  102. mt.EndTiming();
  103. int count = 0;
  104. if (mt.IsLonger(30, 1, true, out count))
  105. {
  106. Console.WriteLine("未能与Web服务器连接,本地ip错误或网络异常");
  107. }
  108. }
  109. }
  110. //});
  111. }
  112. Thread.Sleep(5000);
  113. }
  114. if (multiSocketThread != null)
  115. multiSocketThread.Close();
  116. });
  117. //处理接收到的指令
  118. Task.Factory.StartNew(() =>
  119. {
  120. while (!isClosing)
  121. {
  122. object obj = blockingQueue.Dequeue();
  123. if (obj.GetType().Equals(typeof(MessageUTF8)))
  124. {
  125. MessageUTF8 msg = (MessageUTF8)obj;
  126. switch (msg.cmd)
  127. {
  128. //预约停
  129. case "a":
  130. lock (reserveLock)
  131. {
  132. reserveQueue.Enqueue(msg);
  133. }
  134. //通知PLC减少可预约车位数
  135. //预约记录写入db并更新车辆状态
  136. string vehicleStateChangeSql = "update vehicle set vehiclepParkState =" + 4 + " where numberPlate = '" + msg.context + "';";
  137. Monitor.Monitor.localDBOper.Query(vehicleStateChangeSql);
  138. break;
  139. //预约取
  140. case "b":
  141. break;
  142. //更新广告
  143. case "c":
  144. string adAlert = "";
  145. bool result = Monitor.Monitor.advertMgr.UpdateAdvert(out adAlert);
  146. if (!result)
  147. {
  148. Monitor.Monitor.SetNotification("广告更新失败,请尝试手动更新",parkMonitor.model.TextColor.Error);
  149. }
  150. else
  151. {
  152. Monitor.Monitor.SetNotification("广告更新成功\n" + adAlert,parkMonitor.model.TextColor.Info);
  153. }
  154. break;
  155. default:
  156. Monitor.Monitor.SetNotification("接收到无法识别的指令",parkMonitor.model.TextColor.Warning);
  157. break;
  158. }
  159. }
  160. }
  161. });
  162. //处理超时预约指令
  163. Task.Factory.StartNew(() =>
  164. {
  165. while (!isClosing)
  166. {
  167. lock (reserveLock)
  168. {
  169. for (int i = 0; i < reserveQueue.Count; i++)
  170. {
  171. try
  172. {
  173. MessageUTF8 msg = reserveQueue.Dequeue();
  174. DateTime startTime = DateTime.Parse(msg.bookTime);
  175. if ((DateTime.Now - startTime).TotalMinutes > msg.bookLength * 60)
  176. {
  177. //通知PLC将可预约车位数恢复一个
  178. }
  179. else
  180. {
  181. reserveQueue.Enqueue(msg);
  182. }
  183. }
  184. catch { }
  185. }
  186. }
  187. Thread.Sleep(5000);
  188. }
  189. });
  190. }
  191. private void InsertOrderRecords(string license)
  192. {
  193. string insertSql = "";
  194. List<string> strs = new List<string>();
  195. strs.Add(insertSql);
  196. Monitor.Monitor.localDBOper.Insert(strs);
  197. }
  198. private void DownloadAds()
  199. {
  200. }
  201. /// <summary>
  202. /// 启动
  203. /// </summary>
  204. public bool Start(int port)
  205. {
  206. //string strTemp = ConfigurationManager.AppSettings["WebConfig"];
  207. //string[] strArray = strTemp.Split(':');
  208. //string ipstr = strArray[0];
  209. //string portstr = strArray[1];
  210. //获取本机ip地址
  211. try
  212. {
  213. TcpClient client = new TcpClient();
  214. client.Connect("www.baidu.com", 80);
  215. string ip = ((IPEndPoint)client.Client.LocalEndPoint).Address.ToString();
  216. client.Close();
  217. localAddr = IPAddress.Parse(ip);
  218. this.port = port;//Convert.ToInt32(ConfigurationManager.AppSettings["webPort"]);
  219. reserveQueue = new Queue<MessageUTF8>();
  220. Console.WriteLine(ip.ToString());
  221. }
  222. catch (Exception e) { Console.WriteLine("wrong ipAddr"); return false; }
  223. Run();
  224. return true;
  225. }
  226. /// <summary>
  227. /// 停止
  228. /// </summary>
  229. public void Stop()
  230. {
  231. isClosing = true;
  232. }
  233. /// <summary>
  234. /// 预约停车记录
  235. /// </summary>
  236. public void BookParkRecord()
  237. {
  238. }
  239. /// <summary>
  240. /// 预约取车记录
  241. /// </summary>
  242. public void BookFetchRecord()
  243. {
  244. }
  245. public bool ReservedCarCheck(string license)
  246. {
  247. throw new NotImplementedException();
  248. }
  249. }
  250. }