Signalr信息推送

  前序javascript

    距離上次寫文章,差很少已經大半年了。感受本身愈來愈懶了,即便有時候空閒下來了,也不想動。前面買了一系列的Python的書,基礎的看了大概有四分之一,剩下的基本上還未動,晚上回去也只是吃飯看電影。最近發現頭偶爾開始痛了,歡迎是頸椎出問題,這周準備去看看。但願你們也多注意本身的身體,有什麼 不舒服的及時發現,及時治療。好了,扯遠了,今天無心之間看到了關於Signalr的一些資料和demo,頓時以爲十分有用,遂花了一點時間,參考博友的資料,本身動手作了一個,再次記錄下來,但願能給須要的朋友提供點幫助,也給本身的知識庫增長的養料。有錯誤的地方,還望你們批評指出html

  Signalr簡介java

  ASP .NET SignalR 是一個ASP .NET 下的類庫,能夠在ASP .NET 的Web項目中實現實時通訊。實時通訊:讓客戶端(Web頁面)和服務器端能夠互相通知消息及調用方法,固然這是實時操做的。
jquery

   Signalr使用ajax

   1.新建一個mvc項目。(這裏我使用的是vs2015)  這裏關於MVC的詳細就不贅述了,直接上項目結構,包括頁面、控制器等,可能2015如下的結構有所不一樣。服務器

     

  2.選中項目,添加引用---管理NuGet包程序包,在彈出的對話框中,搜索Signalr,如圖:mvc

    

    點擊安裝,安裝提示步驟一步一步的安裝。app

  3.代碼ide

    a.首先在Startup中app.MapSignalR();註冊SignalR管道。    post

 

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalrPushInformation.Startup))]
namespace SignalrPushInformation
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }
}
View Code

 

  b.添加信息處理類,須要繼承Hub,這裏我統一放在Models文件中。數據存儲因爲我的緣由,這個地方我直接使用了字典的方式,你們能夠存到數據中。

 

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Collections;

namespace SignalrPushInformation.Models
{
    [HubName("PushMessage")]
    public class PushMessage : Hub
    {

        public void Init()
        {
        }

        public void Push(string title, string message)
        {
            this.InsertMsg(title, message);
            // 調用全部客戶端的sendMessage方法
            Clients.All.sendMessage(title, message);
        }
        private void InsertMsg(string title, string message)
        {
            Message msg = new Message();
            msg.Title = title;
            msg.MsgContent = message;
            MsgQueue.Insert(msg);
        }
    }
}
View Code

    這裏須要指出‘sendMessage’方法是自定義的方法,會在客戶端的時候使用,參數與客戶須要一致,名稱隨意。

  c.發送信息view

@{
    ViewBag.Title = "SendMessage";
}
<title>發送消息</title>
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
    $(function () {
        // 引用自動生成的集線器代理,這裏的PushMessage,須要和信息處理類名稱一致
        var chat = $.connection.PushMessage;
        // 定義服務器端調用的客戶端sendMessage來顯示新消息,sendMessage方法須要信息處理類中的方法一致,參數一致
        chat.client.sendMessage = function (title, message) {
            // 向頁面發送接收的消息
            sendMsg();
        };
        // 集成器鏈接開始,
        $.connection.hub.start()
            .done(function () {
                // 服務鏈接完成,給發送按鈕註冊單擊事件
                $('#sendmessage').click(function () {
                    // 調用服務器端集線器的Send方法,push方法須要信息處理類中的方法一致
                    chat.server.push($("#title").val(), $('#message').val());
                });
                sendMsg();
            })
            .fail(function () {
                console.log("Could not Connect!");
            });
    });

    function sendMsg() {
        var options = {
            url: '/Message/MsgCount',
            type: 'post',
            success: function (data) {
                $("#count").html(data.count);
            }
        };
        $.ajax(options);
    }
</script>


<h2>
    發送消息
</h2>
<div>
    <label>個人消息:</label>
    <span style=" color:red; font-size:30px;" id="count"></span></div>
<p>
    <div>
        標題:
        <input type="text" id="title" />
    </div>
    <br /><br />
    <div>
        內容:
        <textarea id="message" rows="4" cols="30"></textarea>
    </div>
    <br /><br />
    <div>
        <input type="button" id="sendmessage" value="發送" />
    </div>
</p>
View Code

  d.接收信息view

@{
    ViewBag.Title = "ReceiveMessage";
}

<title>接受消息</title>
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
    $(function () {
        // 引用自動生成的集線器代理
        var chat = $.connection.PushMessage;
        // 定義服務器端調用的客戶端sendMessage來顯示新消息,sendMessage方法須要信息處理類中的方法一致,參數一致
        chat.client.sendMessage = function (title, message) {
            // 向頁面發送接收的消息
            MsgCount(false);
            $("#msgcontent").after("<div>標題:" + title + ",消息內容:" + message + "</div>");
        };
        // 集成器鏈接開始
        $.connection.hub.start().done(function () {
            MsgCount(true);
        }).fail(function () {
            console.log("Could not Connect!");
        });
    });
    function MsgCount(init) {
        var options = {
            url: '/Message/MsgCount',
            type: 'post',
            success: function (data) {
                if (data != null) {
                    $("#count").html(data.count);
                    console.log(data.msg);
                    if (init) {
                        $.each(data.msg, function (n, m) {
                            $("#msgcontent").append("<div>標題:" + m.Title + ",消息內容:" + m.MsgContent + "</div>");
                        });
                    }
                }
            }
        };
        $.ajax(options);
    }
</script>


<h2>
    接收消息
</h2>

<div>
    <label>個人消息:</label>
    <span style="color: red; font-size: 30px; margin-right:10px;" id="count"></span><br />
    <br />
    <div id="msgcontent"></div>
</div>
View Code

  f.控制器代碼

using SignalrPushInformation.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SignalrPushInformation.Controllers
{
    public class MessageController : Controller
    {
        // GET: Message
        public ActionResult ReceiveMessage()
        {
            return View();
        }

        public ActionResult SendMessage()
        {
            MsgQueue.Insert(new Message()
            {
                MsgContent = "zcy",
                Title = "zcy"
            });
            return View();
        }
        [HttpPost]
        public JsonResult MsgCount()
        {
            return Json(new { count = MsgQueue.GetCount(), msg = MsgQueue.Dequeue() });
        }
    }
}
View Code

  好了,一切都OK了,只須要編譯生成,執行就行。詳細的解釋已經所有在代碼中了,這個地方就不詳細的說明。

  留在最後

    從開通博客到如今,了了的幾篇文章,發現本身真的是太懶了。有時感受真的不善於表達,想寫點什麼,可是不知道怎麼寫。後續的想對Python寫一個系列,加深對Python的理解。雖然前面完整的看過一次基礎的教程,可是發現仍是有不少不懂的地方,但願以博客的造成,能加深本身的理解,也想改掉本身懶的毛病,,但願能讓博客來監督我吧。

    最後老規矩,源碼!(密碼:MT4E)

相關文章
相關標籤/搜索