跨外網絡雲服務器推送消息到每個客戶端ASP.NET SignalR

SignalR

ASP.NET SignalR 是爲 ASP.NET 開發人員提供的一個庫,可以簡化開發人員將實時 Web 功能添加到應用程序的過程。實時 Web 功能是指這樣一種功能:當所連接的客戶端變得可用時服務器代碼可以立即向其推送內容,而不是讓服務器等待客戶端請求新的數據。

服務端:控制檯應用程序----可以看到客戶端連接掉線的消息,給那個客戶端發送了消息

客戶端:windows服務---通過命令註冊到windows服務裏開機自動啓動用到Topshelf、定時調度Quartz,同時客戶端又是一個服務端來給UDP客戶端發送消息。

廢話不多說直接上代碼

服務端實現如下:

1、新建控制檯程序起名叫SignalRServer

2、引入如下nuget包

Microsoft.AspNet.SignalR
Microsoft.Owin
Microsoft.Owin.Cors
Microsoft.Owin.Host.HttpListener
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Hosting
Microsoft.Owin.Security
Topshelf
log4net

 新建一個集線器類BroadcastHub繼承Hub

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalRServer.Entity
{
    public class BroadcastHub : Hub
    {
        private readonly BroadcastContext broadcastContext;
        public List<string> clientNames = new List<string>();
        public BroadcastHub()
        {
            broadcastContext = BroadcastContext.Instance;
        }

        /// <summary>
        /// 重寫連接事件
        /// </summary>
        /// <returns></returns>
        public override Task OnConnected()
        {
            //http://localhost:1025/signalr/start?clientProtocol=2.1&transport=webSockets&connectionData=[%7B%22Name%22:%22BroadcastHub%22%7D]&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAAXuODpT5BCkiFAeRnu6KQGAAAAAACAAAAAAAQZgAAAAEAACAAAABL%2Bx9m6PIYP7fywds%2BvYNZf93gFbIeayz3qP9VGoOQhwAAAAAOgAAAAAIAACAAAABuWj%2F%2FqzXpcnhuxsK8JHjIy3I7e7b5BxSgmDnnb263vTAAAACyf0G%2BPfivCw2YD6bWoaUYzYAU0OWyg4I%2FQyR1aWOPpv87GBHAoMzpYO3%2BDlkF6xxAAAAAiwLJIGVbN5O8zUekVOn9DkaI2OuQIdTrnWIxI%2BTqt7LZh7QvnUdZ3CEkH2fmmpiz60L7%2BMQsLkWKzIyCmMg%2BtA%3D%3D&clientName=1C1B0D29912A
            try
            {
                //通過url地址截取識別那個客戶端
                string[] urlstr = Context.Request.Url.Query.Split('&');
                string clientNamedic = urlstr[4].Split('=')[1];

                if (!CommonUser.clientNames.ContainsKey(clientNamedic))
                {
                    //給客戶端起名識別客戶端然後把clientid保存起來
                    Console.WriteLine("設備id爲 " + clientNamedic + " 連接成功!");
                    CommonUser.clientNames.Add(clientNamedic, Context.ConnectionId);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message.ToString(), ex);
            } 
            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            try
            {
                string ConnectionIdstr = Context.ConnectionId;
                if (CommonUser.clientNames.ContainsValue(ConnectionIdstr))
                {
                    var firstKey = CommonUser.clientNames.FirstOrDefault(q => q.Value == ConnectionIdstr).Key;
                    CommonUser.clientNames.Remove(firstKey);
                    Console.WriteLine("設備id爲 " + firstKey + " 已離線!");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message.ToString(), ex);
            }
           
            return base.OnDisconnected(stopCalled);
        }
    }
}

新建一個廣播類BroadcastContext

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalRServer.Entity
{
    public class BroadcastContext
    {
        //單例模式 所有客戶端都共用此實例 才能達到廣播的效果
        private static readonly BroadcastContext instance =
        new BroadcastContext(GlobalHost.ConnectionManager.GetHubContext<BroadcastHub>());

        private readonly IHubContext context;
        //功能業務類
        private readonly FunctionApp functionApp;

        public static BroadcastContext Instance
        {
            get { return instance; }
        }

        private BroadcastContext(IHubContext context)
        {
            this.context = context;
            functionApp = new FunctionApp(context);
            functionApp.Action();
        }
    }
}

新建一個上下文類FunctionApp

using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace SignalRServer.Entity
{
    public class FunctionApp
    {
        //上下文
        private readonly IHubContext context;
        static object locker = new object(); // !!
        private static CancellationTokenSource cts = new CancellationTokenSource();
        public FunctionApp(IHubContext context)
        {
            this.context = context;

        }

        public void Action()
        {
            //測試廣播功能
            Task.Run(() => Start());
        }

        private void Start()
        {
            try
            {
                string url = ConfigurationManager.AppSettings["dataurl"];
                var token = cts.Token;
                while (true)
                {
                    try

                    {
                        //控制併發用的Parallel
                        Parallel.ForEach(CommonUser.clientNames, new ParallelOptions { MaxDegreeOfParallelism = 10, CancellationToken = token }, client =>
                        {
                            //foreach (var item in CommonUser.clientNames)
                            //{
                            //客戶端調用的方法名必須一致
                            //讀取數據的地方,我是讀取接口數據
                            string response = HttpUtils.Get(url + client.Key);
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            var req = js.Deserialize<JsonResultData>(response.ToString());
                            if (req.errorcode != 2)
                            {
                                if (CommonUser.clientNames.ContainsKey(client.Key))
                                {
                                    string json = JsonConvert.SerializeObject(req.data);
                                    Console.WriteLine("向設備id爲" + client.Key + " 發送=》" + json);
                                    context.Clients.Client(CommonUser.clientNames[client.Key]).ReceiveMsg(json);
                                }

                            }
                            //if (CommonUser.clientNames.ContainsKey("1C1B0D29912A"))
                            //{
                            //    context.Clients.Client(CommonUser.clientNames["1C1B0D29912A"]).ReceiveMsg("11122");
                            //}

                            // }
                            Thread.Sleep(1000);
                        });
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(ex.Message.ToString(), ex);
                    }
                   
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message.ToString(), ex);
            }
        }
    }
    public class JsonResultData
    {
        /// <summary>
        /// 返回編碼0執行成功/數據上傳成功1執行失敗100請求的服務不存在200數據格式錯誤
        /// </summary>
        public int errorcode { set; get; }
        /// <summary>
        /// 提示信息
        /// </summary>
        public string message { set; get; }
        /// <summary>
        /// 附加信息
        /// </summary>
        public object data { set; get; }

    }
}

新建一個用來存取客戶端的內存類CommonUser

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalRServer.Entity
{
    public class CommonUser
    {
        public static Dictionary<string, string> clientNames = new Dictionary<string, string>();
    }
}

新建一個http獲取接口數據的get和post公共類

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SignalRServer.Entity
{
    //獲取第三方api的工具類
    public class HttpUtils
    {
        public static string Get(string Url)
        {
            //System.GC.Collect();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }

            return retString;
        }

        public static string Post(string Url, string Data, string Referer)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.Referer = Referer;
            byte[] bytes = Encoding.UTF8.GetBytes(Data);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream myResponseStream = request.GetRequestStream();
            myResponseStream.Write(bytes, 0, bytes.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            return retString;
        }
    }
}

新建一個Startup類

using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Cors;
namespace SignalRServer
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
        }
    }
}

新建一個服務類爲了能運用topshelf注入到windows服務裏SignalService

using Microsoft.Owin.Hosting;
using System;
using System.Configuration;
namespace SignalRServer.Entity
{
    public class SignalService
    {
        static string url = ConfigurationManager.AppSettings["url"];
        public void Start()
        {
            //業務處理
            WebApp.Start<Startup>(url);
            Console.WriteLine("遠程服務啓動成功!");
            Console.ReadKey();
        }

        public void Stop()
        {

        }
    }
}

新建一個lognet日誌類LogHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalRServer
{
    public class LogHelper
    {
        public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("ServerInfo");
        public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("ServerError");
        public static void WriteLog(string info)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(info);
            }
        }

        public static void WriteLog(string info, Exception ex)
        {
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(info, ex);
            }
        }
    }
}

新建一個日誌config

<?xml version="1.0" encoding="utf-8"?>
<log4net>
  <!--錯誤日誌類-->
  <logger name="logerror">
    <!--日誌類的名字-->
    <level value="ALL" />
    <!--定義記錄的日誌級別-->
    <appender-ref ref="ErrorAppender" />
    <!--記錄到哪個介質中去-->
  </logger>
  <!--信息日誌類-->
  <logger name="loginfo">
    <level value="ALL" />
    <appender-ref ref="InfoAppender" />
  </logger>
  <!--錯誤日誌附加介質-->
  <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
    <!-- name屬性指定其名稱,type則是log4net.Appender命名空間的一個類的名稱,意思是,指定使用哪種介質-->
    <param name="File" value="D:\\Log\\SinalRServerLog\\" />
    <!--日誌輸出到exe程序這個相對目錄下-->
    <param name="AppendToFile" value="true" />
    <!--輸出的日誌不會覆蓋以前的信息-->
    <param name="MaxSizeRollBackups" value="100" />
    <!--備份文件的個數-->
    <param name="MaxFileSize" value="10240" />
    <!--當個日誌文件的最大大小-->
    <param name="StaticLogFileName" value="false" />
    <!--是否使用靜態文件名-->
    <param name="DatePattern" value="yyyyMMdd&quot;.htm&quot;" />
    <!--日誌文件名-->
    <param name="RollingStyle" value="Date" />
    <!--文件創建的方式,這裏是以Date方式創建-->
    <!--錯誤日誌佈局-->
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="&lt;HR COLOR=red&gt;%n異常時間:%d [%t] &lt;BR&gt;%n異常級別:%-5p &lt;BR&gt;%n異 常 類:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;"  />
    </layout>
  </appender>
  <!--信息日誌附加介質-->
  <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="Log\\LogInfo\\" />
    <param name="AppendToFile" value="true" />
    <param name="MaxFileSize" value="10240" />
    <param name="MaxSizeRollBackups" value="100" />
    <param name="StaticLogFileName" value="false" />
    <param name="DatePattern" value="yyyyMMdd&quot;.htm&quot;" />
    <param name="RollingStyle" value="Date" />
    <!--信息日誌佈局-->
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="&lt;HR COLOR=blue&gt;%n日誌時間:%d [%t] &lt;BR&gt;%n日誌級別:%-5p &lt;BR&gt;%n日 志 類:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;"  />
    </layout>
  </appender>
</log4net>

修改應用程序的入口Program文件

using SignalRServer.Entity;
using Topshelf;

namespace SignalRServer
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(c =>
            {
                c.SetServiceName("SignalRServerServices");
                c.SetDisplayName("SignalRServerServices");
                c.SetDescription("SignalRServerServices");

                c.Service<SignalService>(s =>
                {
                    s.ConstructUsing(b => new SignalService());
                    s.WhenStarted(o => o.Start());
                    s.WhenStopped(o => o.Stop());
                });
            });
        }
    }
}

修改app.config文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="dataurl" value="" />
    <!--阿里雲一定要用*來代替ip地址-->
    <add key="url" value="http://*:5000" />
  </appSettings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

服務端源碼地址:https://download.csdn.net/download/it_ziliang/11250515

客戶端源碼地址:https://download.csdn.net/download/it_ziliang/11250526

 

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