您当前的位置:首页 > 文章 > C#使用WebSocket实现服务器推送

C#使用WebSocket实现服务器推送消息至前端

作者:新鑫S 时间:2024-02-28 阅读数:202 人阅读

最近做的web项目中,需要服务器直接触发前端显示效果。

思路:服务端后端定时查询数据库数据,建立一个Socket服务端,前端WebSocket模拟http请求连接Socket,长连接接收消息,处理之后在页面上显示。

WebSocket

WebSocket协议是一种双向通信协议,它建立在TCP之上,同http一样通过TCP来传输数据,但是它和http最大的不同有两点:

1、WebSocket是一种双向通信协议,在建立连接后,WebSocket服务器和Browser/UA都能主动的向对方发送或接收数据,就像Socket一样,不同的是WebSocket是一种建立在Web基础上的一种简单模拟Socket的协议;

2、WebSocket需要通过握手连接,类似于TCP它也需要客户端和服务器端进行握手连接,连接成功后才能相互通信。 当Web应用程序调用new WebSocket(url)接口时,Browser就开始了与地址为url的WebServer建立握手连接的过程。

C#后端代码:

using Newtonsoft.Json;
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;

namespace Client
{
    public class WebSocket
    {
        private static Socket listener;
        private static Hashtable ht;

        private static List<Inform> list = new List<Inform>();
        private static string str = string.Format("select * from inform where state = 'true'");
        private static DataTable dt = SQLHelper.ExecuteDataTable(str);

        //通知类
        private class Inform
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public bool State { get; set; }
        }

        public static void Start()
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Inform data = new Inform();
                data.Id = int.Parse(dt.Rows[i]["id"].ToString());
                data.Name = dt.Rows[i]["name"].ToString();
                data.State = bool.Parse(dt.Rows[i]["state"].ToString());
                list.Add(data);
            }

            int port = 9000;//监听端口为9000端口
            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-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);
            Console.WriteLine("接收到客户端信息:" + xm);

            clientSocket.Send(PackData("连接时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            try
            {
                while (true)
                {
                    //异常客户端
                    var errLs = new List<object>();

                    //发送数据
                    List<Inform> inform_list = new List<Inform>();
                    DataTable inform_dt = SQLHelper.ExecuteDataTable(string.Format("select * from inform where state = 'true'"));
                    for (int i = 0; i < inform_dt.Rows.Count; i++)
                    {
                        Inform data = new Inform();
                        data.Id = int.Parse(inform_dt.Rows[i]["id"].ToString());
                        data.Name = inform_dt.Rows[i]["name"].ToString();
                        data.State = bool.Parse(inform_dt.Rows[i]["state"].ToString());
                        inform_list.Add(data);
                    }

                    //对比list
                    var exp = inform_list.Where(a => (!list.Exists(t => t.Id.Equals(a.Id) && t.State == a.State))).ToList();

                    //如果数据发生了变化,则发送
                    if (exp.Count() > 0)
                    {
                        var sendRet = (from a in exp
                                       select new
                                       {
                                           inform_id = a.Id,
                                           inform_name = a.Name,
                                           inform_state = a.State
                                       }).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));
                                list = inform_list;//inform_list.GetRange(0, inform_list.Count);
                                byte[] back = new byte[1024];
                                try
                                {
                                    //接收客户端信息
                                    int back_length = sc.Receive(back);
                                    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);
                            }
                        }
                    }
                    //删除hashTable中的异常客户端数据
                    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="handShakeBytes"></param>
        /// <param name="bytesLength"></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
let ws = new WebSocket("ws://199.168.22.252:9000");
ws.onopen = function (e) {
    ws.send('{ws://199.168.22.252:9000}');
};
ws.onmessage = function (e) {
    console.log(e)
    console.log(e.data);
    var data_list = JSON.parse(e.data);
    console.log(data_list)
//处理消息,在页面展示内容(自由扩展)
    ws.send('1');//发送消息给后台
};
ws.onerror = function (e) {
    alert("网络连接错误!");
};
ws.onclose = function (e) {
    alert("服务器断开!");
};



本站大部分文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了您的权益请来信告知我们删除。邮箱:1451803763@qq.com