c#後臺定時查庫,socket給前臺發送消息,前臺websocket接收消息;取代前端輪詢查庫;

後臺代碼:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Reflection;
using client;

namespace client
{
  public class WebClient
    {

        private static Socket listener;
        private static Hashtable ht;
       private static string esdStr = string.Format("select * From esd");
       private static DataTable db_esd = SQLHelper.ExecuteDataTable(esdStr);
       private  class Esd
       {
           public System.Guid Esd_ID { get; set; }
           public string Esd_Num { get; set; }
           public string Esd_Name { get; set; }
           public string Esd_Area { get; set; }
           public string Esd_Status { get; set; }
           public Nullable<System.DateTime> Esd_UpTime { get; set; }
           public string Esd_CalArea { get; set; }
           public string Esd_CrNate { get; set; }
       }
       private static List<Esd> esd_list = CommonTransafer.ToList<Esd>(db_esd);
        public  void Start()
        { 
        
            int port = 9002;//監聽端口爲1818端口
            ht = new Hashtable();//用於存放客戶端的連接socket
            byte[] buffer = new byte[1024];

            var localEP = new IPEndPoint(IPAddress.Any, port);
            listener = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(localEP);
                listener.Listen(100);

                Console.WriteLine("等待客戶端連接....");
                while (true)
                {
                    Socket clientSocket = listener.Accept(); //接收到客戶端的連接      
                    var th = new Thread(new ParameterizedThreadStart(Receive));
                    th.Start(clientSocket);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        
        }
        /// <summary>
        /// 線程調用
        /// </summary>
        private static void Receive(object o)//Socket clientSocket)
        {
            Socket clientSocket = (Socket)o;
            clientSocket.Blocking = true;
            IPEndPoint clientipe = (IPEndPoint)clientSocket.RemoteEndPoint;
            //    Console.WriteLine("[" + clientipe.Address.ToString() + "] Connected");
            var key = string.Format("{0}-X-Q-X-{1}", clientipe.Address.ToString(), clientipe.Port);
            if (!ht.ContainsKey(key))
            {
                //將ip地址設置爲hashTable的key值 若hashTable中存在該ip地址則不再ht中添加socket以免發送重複數據
                ht.Add(key, clientSocket);
            }
            Console.WriteLine("接收到了客戶端:ip" + clientSocket.RemoteEndPoint.ToString() + "的連接");
            byte[] buffer = new byte[1024];
            int length = clientSocket.Receive(buffer);
            clientSocket.Send(PackHandShakeData(GetSecKeyAccetp(buffer, length)));
            Console.WriteLine("已經發送握手協議了....");

            //接收用戶姓名信息
            //length = clientSocket.Receive(buffer);
            //string xm = AnalyticData(buffer, length);

            //clientSocket.Send(PackData("連接時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            try
            {

                while (true)
                {
                    var errLs = new List<object>();
                    //發送數據
                    string dtStr = string.Format("select * From esd");
                    DataTable db_device = SQLHelper.ExecuteDataTable(dtStr);
                    var device_list=CommonTransafer.ToList<Esd>(db_device);
                    //對比list
                    var exp = device_list.Where(a => (!esd_list.Exists(t => t.Esd_Status.Equals(a.Esd_Status) && t.Esd_ID.Equals(a.Esd_ID) && t.Esd_Num.Equals(a.Esd_Num) && t.Esd_Name.Equals(a.Esd_Name) && t.Esd_Area.Equals(a.Esd_Area) && t.Esd_Status.Equals(a.Esd_Status) && t.Esd_UpTime.Equals(a.Esd_UpTime) && t.Esd_CalArea.Equals(a.Esd_CalArea) && t.Esd_CrNate.Equals(a.Esd_CrNate)))).ToList();

                    //對比datatable
                    //IEnumerable<DataRow> query2 = db_device.AsEnumerable().Except(db_esd.AsEnumerable(), DataRowComparer.Default).ToList();
                    //var normalReceive = from r in db_esd.AsEnumerable()
                    //                    where
                    //                    !(from rr in db_device.AsEnumerable() select rr.Field<string>("Esd_UpTime")).Contains(
                    //                    r.Field<string>("Esd_UpTime"))
                    //                    select r;

                    //如果數據發生了變化,則發送
                    if (exp.Count() > 0)
                    {
                        var sendRet = (from a in exp
                                  select new
                                  {
                                      device_area=a.Esd_Area,
                                      device_alarm=a.Esd_Status,
                                      device_time=a.Esd_UpTime

                                  }).ToList();
                    string ret = JsonConvert.SerializeObject(sendRet);
                    Console.WriteLine("發送數據:“" + ret + "” 至客戶端....");
                    //遍歷hashTable中的數據獲取Socket發送數據
                    foreach (DictionaryEntry de in ht)
                    {
                        try
                        {
                            var sc = (Socket)de.Value;
                            sc.Send(PackData_new(ret));
                            esd_list = device_list.GetRange(0, device_list.Count);
                            //byte[] back = new byte[1024];
                            //try
                            //{

                            //int back_length = sc.Receive(back);
                            //string xm = AnalyticData(back, back_length);
                            //if (back_length==0)
                            //{
                            //    errLs.Add(de.Key);
                            //}
                            //}
                            //catch (Exception)
                            //{
                            //   errLs.Add(de.Key);
                            //}

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Num:{0} err:{1}", ht.Count, e);
                            errLs.Add(de.Key);
                        }
                    }
                    }

                    if (errLs != null && errLs.Any())
                    {
                        foreach (var item in errLs)
                        {
                            ht.Remove(item);
                        }
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (SocketException e)
            {
                //去除字典
                Console.WriteLine(e.Message);
            }
            catch (System.ObjectDisposedException e)
            {
                //去除字典
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


        }

        /// <summary>
        /// 打包握手信息
        /// </summary>
        /// <param name="secKeyAccept">Sec-WebSocket-Accept</param>
        /// <returns>數據包</returns>
        private static byte[] PackHandShakeData(string secKeyAccept)
        {
            var responseBuilder = new StringBuilder();
            responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);
            responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);
            responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);
            responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);
            //如果把上一行換成下面兩行,纔是thewebsocketprotocol-17協議,但居然握手不成功,目前仍沒弄明白!
            //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);
            //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);

            return Encoding.UTF8.GetBytes(responseBuilder.ToString());
        }

        /// <summary>
        /// 生成Sec-WebSocket-Accept
        /// </summary>
        /// <param name="handShakeText">客戶端握手信息</param>
        /// <returns>Sec-WebSocket-Accept</returns>
        private static string GetSecKeyAccetp(byte[] handShakeBytes, int bytesLength)
        {
            string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);
            string key = string.Empty;
            Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
            Match m = r.Match(handShakeText);
            if (m.Groups.Count != 0)
            {
                key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
            }
            byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
            return Convert.ToBase64String(encryptionString);
        }

        /// <summary>
        /// 解析客戶端數據包
        /// </summary>
        /// <param name="recBytes">服務器接收的數據包</param>
        /// <param name="recByteLength">有效數據長度</param>
        /// <returns></returns>
        private static string AnalyticData(byte[] recBytes, int recByteLength)
        {
            if (recByteLength < 2) { return string.Empty; }

            bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最後一幀  
            if (!fin)
            {
                return string.Empty;// 超過一幀暫不處理 
            }

            bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩碼  
            if (!mask_flag)
            {
                return string.Empty;// 不包含掩碼的暫不處理
            }

            int payload_len = recBytes[1] & 0x7F; // 數據長度  

            byte[] masks = new byte[4];
            byte[] payload_data;

            if (payload_len == 126)
            {
                Array.Copy(recBytes, 4, masks, 0, 4);
                payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 8, payload_data, 0, payload_len);

            }
            else if (payload_len == 127)
            {
                Array.Copy(recBytes, 10, masks, 0, 4);
                byte[] uInt64Bytes = new byte[8];
                for (int i = 0; i < 8; i++)
                {
                    uInt64Bytes[i] = recBytes[9 - i];
                }
                UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0);

                payload_data = new byte[len];
                for (UInt64 i = 0; i < len; i++)
                {
                    payload_data[i] = recBytes[i + 14];
                }
            }
            else
            {
                Array.Copy(recBytes, 2, masks, 0, 4);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 6, payload_data, 0, payload_len);

            }

            for (var i = 0; i < payload_len; i++)
            {
                payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]);
            }

            return Encoding.UTF8.GetString(payload_data);
        }


        /// <summary>
        /// 打包服務器數據
        /// </summary>
        /// <param name="message">數據</param>
        /// <returns>數據包</returns>
        private static byte[] PackData(string message)
        {
            byte[] contentBytes = null;
            byte[] temp = Encoding.UTF8.GetBytes(message);

            if (temp.Length < 126)
            {
                contentBytes = new byte[temp.Length + 2];
                contentBytes[0] = 0x81;
                contentBytes[1] = (byte)temp.Length;
                Array.Copy(temp, 0, contentBytes, 2, temp.Length);
            }
            else if (temp.Length < 0xFFFF)
            {
                contentBytes = new byte[temp.Length + 4];
                contentBytes[0] = 0x81;
                contentBytes[1] = 126;
                contentBytes[2] = (byte)(temp.Length & 0xFF);
                contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);
                Array.Copy(temp, 0, contentBytes, 4, temp.Length);
            }
            else
            {
                // 暫不處理超長內容  
            }

            return contentBytes;
        }


        /// <summary>
        /// 打包服務器數據(處理超長數據)
        /// </summary>
        /// <param name="message">數據</param>
        /// <returns>數據包</returns>
        public static byte[] PackData_new(string message)
        {
            byte[] contentBytes = null;
            byte[] temp = Encoding.UTF8.GetBytes(message);
            if (temp.Length < 126)
            {
                contentBytes = new byte[temp.Length + 2];
                contentBytes[0] = 0x81;
                contentBytes[1] = (byte)temp.Length;
                Array.Copy(temp, 0, contentBytes, 2, temp.Length);
            }
            else if (temp.Length < 0xFFFF)
            {
                contentBytes = new byte[temp.Length + 4];
                contentBytes[0] = 0x81;
                contentBytes[1] = 126;
                contentBytes[2] = (byte)(temp.Length >> 8);
                contentBytes[3] = (byte)(temp.Length & 0xFF);
                Array.Copy(temp, 0, contentBytes, 4, temp.Length);
            }
            else
            {
                contentBytes = new byte[temp.Length + 10];
                contentBytes[0] = 0x81;
                contentBytes[1] = 127;
                contentBytes[2] = 0;
                contentBytes[3] = 0;
                contentBytes[4] = 0;
                contentBytes[5] = 0;
                contentBytes[6] = (byte)(temp.Length >> 24);
                contentBytes[7] = (byte)(temp.Length >> 16);
                contentBytes[8] = (byte)(temp.Length >> 8);
                contentBytes[9] = (byte)(temp.Length & 0xFF);
                Array.Copy(temp, 0, contentBytes, 10, temp.Length);
            }

            return contentBytes;
        }
    }
}
 

 

 

前端代碼:

  //連接websocket
       function connect() {
           ws = new WebSocket("ws://192.168.10.103:9002");
           ws.onopen = function (e) {
               ws.send('{ws://192.168.10.103:9002}');
           };
           ws.onmessage = function (e) {
               var data_list = JSON.parse(e.data);
             //處理消息,在頁面展示內容(自由擴展)
               //ws.send('{1}');發送消息給後臺

           };
           ws.onerror = function (e) {
               alert("網絡連接錯誤!");
           };
           ws.onclose = function (e) {
               alert("服務器斷開!");
           };
       };

 

參考:http://www.cnblogs.com/xqaizx/p/9446863.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章