using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using parkMonitor.entity; using System.Configuration; using System.Net.Sockets; using System.Net; using System.Threading; using parkMonitor.tools; namespace WebServer { /// /// web线程类,接收用户指令 /// public class CentralForWeb : IWebServer { public MultiSocketThread multiSocketThread { set; get; } public static BlockingQueue blockingQueue = new BlockingQueue(); Int32 port; IPAddress localAddr; bool isClosing; //public AbstractMessage GetMessage() //{ // return (AbstractMessage)blockingQueue.Dequeue(); //} private void WebConnect(TcpListener listener) { try { if (listener != null) { //得到包含客户端信息的套接字 var tcpClient = listener.AcceptTcpClient(); //创建消息服务线程对象 //把multiSocket类的run方法委托给线程 multiSocketThread = new MultiSocketThread(tcpClient); Thread newThread = new Thread(multiSocketThread.Run); newThread.IsBackground = true; newThread.Start(); } } catch (Exception e) { if (multiSocketThread != null) multiSocketThread.Close(); Console.WriteLine(e.Message); throw new Exception(); } } private void Run() { bool linked = false; Task.Factory.StartNew(() => { TcpListener listener = null; try { listener = LazySingleton.GetInstance(localAddr, port); listener.Start(); linked = true; } catch (Exception) { Console.WriteLine("未能与Web服务器连接,本地ip错误或网络异常"); linked = false; } while (isClosing) { try { while (linked) { WebConnect(listener); } if (!linked) { throw new Exception(); } } catch (Exception) { //Task.Factory.StartNew(() => //{ MyTimer mt = new MyTimer(); mt.StartTiming(); while (!linked) { Thread.Sleep(10000); try { listener = LazySingleton.GetInstance(localAddr, port); listener.Start(); linked = true; Console.WriteLine("web已成功重连"); break; } catch (Exception) { mt.EndTiming(); int count = 0; if (mt.IsLonger(30, 1, true, out count)) { Console.WriteLine("未能与Web服务器连接,本地ip错误或网络异常"); } } } //}); } Thread.Sleep(5000); } if (multiSocketThread != null) multiSocketThread.Close(); }); } private void DownloadAds() { } /// /// 启动 /// public bool Start(int port) { //string strTemp = ConfigurationManager.AppSettings["WebConfig"]; //string[] strArray = strTemp.Split(':'); //string ipstr = strArray[0]; //string portstr = strArray[1]; //获取本机ip地址 try { TcpClient client = new TcpClient(); client.Connect("www.baidu.com", 80); string ip = ((IPEndPoint)client.Client.LocalEndPoint).Address.ToString(); client.Close(); localAddr = IPAddress.Parse(ip); this.port = port;//Convert.ToInt32(ConfigurationManager.AppSettings["webPort"]); Console.WriteLine(ip.ToString()); } catch (Exception e) { Console.WriteLine("wrong ipAddr");return false; } Run(); return true; } /// /// 停止 /// public void Stop() { isClosing = true; } /// /// 停车预约 /// public void ParkBooking() { } /// /// 取车预约 /// public void FetchBooking() { } /// /// 预约停车记录 /// public void bookParkRecord() { } /// /// 预约取车记录 /// public void bookFetchRecord() { } } }