溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

.Net使用SignalR實現(xiàn)消息推送功能預(yù)研及Demo

發(fā)布時間:2020-07-03 21:32:20 來源:網(wǎng)絡(luò) 閱讀:6571 作者:tongling_zzu 欄目:編程語言

所需環(huán)境:SignalR運行在.NET 4.5平臺上,這里演示時采用ASP.NET MVC 3;

一.簡介

ASP .NET SignalR 是一個ASP .NET 下的類庫,可以在ASP .NET 的Web項目中實現(xiàn)實時通信。

二.原理

其實現(xiàn)原理跟WCF或Remoting相似,均為使用遠程代理來實現(xiàn)。實現(xiàn)接口有2種分別是PersistentConnection 和 Hubs,其中PersistentConnection 是實現(xiàn)長時間js輪循的,Hub是用來解決實時信息交換問題,其利用js動態(tài)載入方法實現(xiàn),客戶端與服務(wù)器端全部使用json來交換數(shù)據(jù)。

三.Demo創(chuàng)建

1.打開NuGet 安裝 Microsoft ASP.NET SignalR

.Net使用SignalR實現(xiàn)消息推送功能預(yù)研及Demo

  2.實現(xiàn)

a).實現(xiàn)PersistentConnection

添加myconnection.cs文件

namespace MvcApplicationSignalR
{
   public  class myconnection : PersistentConnection
    {
        protected override Task OnReceivedAsync(string clientId, string data)
        {
            // Broadcast data to all clients
            data = string.Format("數(shù)據(jù)是:{0} 時間是:{1}", data, DateTime.Now.ToString());
            //return Connection.Broadcast(data);
            return Send(clientId, data);
        }
    }
}

在Global.asax.cs文件中注冊一下代碼(第3行):

protected void Application_Start()
{
      RouteTable.Routes.MapConnection<myconnection>("echo","echo/{*operation}");
                                                                                                                                                                                               
      AreaRegistration.RegisterAllAreas();
      RegisterGlobalFilters(GlobalFilters.Filters);
      RegisterRoutes(RouteTable.Routes);
}

在前臺頁面中添加如下html代碼:

<script type="text/javascript">
    $(function () {
        var connection = $.connection('echo');
        connection.received(function (data) {
            $('#messages').append('<li>' + data + '</li>');
        });
        connection.start();
        $("#broadcast").click(function () {
            connection.send($('#msg').val());
        });
        $("#btnStop").click(function () {
            connection.stop();
        });
    });
</script>
<h3>@ViewBag.Message</h3>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="發(fā)送" />
<input type="button" id="btnStop" value="停止" />
<ul id="messages">
</ul>

執(zhí)行效果如下:

.Net使用SignalR實現(xiàn)消息推送功能預(yù)研及Demo

可在

protectedoverrideTask OnReceivedAsync(stringclientId, stringdata)

方法中進行消息的監(jiān)視。

b).實現(xiàn)Hubs

新建Chat.cs類,代碼如下:

namespace MvcApplicationSignalR
{
    [HubName("chat")]
    public class Chat : Hub
    {
        public void Send(string clientName, string message)
        {
            Clients.addSomeMessage(clientName, message);
        }
    }
}

前臺模板html代碼如下:

<head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
        <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-1.6.4.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-ui-1.8.24.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.signalR-0.5.3.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
    </head>

后臺代碼如下:

public ActionResult HubChat()
{
    ViewBag.ClientName = "用戶-" + Rnd.Next(1, 9);
    return View();
}

對應(yīng)的視圖代碼為:

@model dynamic
@{
    ViewBag.Title = "title";
}
<script src="@Url.Content("~/Scripts/hubDemo.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
    });
</script>
<h3>Hub Chat</h3>
<div>
    <input type="text" id="Placeholder" value="@ViewBag.ClientName" hidden="true"/>
    <input type="text" id="msg" />
    <input type="button" id="broadcast" value="廣播" />
                                       
    <br />
    <br />
    <h4>
        消息記錄: (你是:<span id="MyClientName">@ViewBag.ClientName</span>):
    </h4>
    <ul id="messages">
    </ul>
</div>

hubDemo.js所對應(yīng)的內(nèi)容如下:

$(function () {
    var myClientName = $('#Placeholder').val();
    // Proxy created on the fly
    var chat = $.connection.chat;
    // Declare a function on the chat hub so the server can invoke it
    chat.addSomeMessage = function (clientName, message) {
        writeEvent('<b>' + clientName + '</b> 對大家說: ' + message, 'event-message');
    };
    $("#broadcast").click(function () {
        // Call the chat method on the server
        chat.send(myClientName, $('#msg').val())
                            .done(function () {
                                console.log('Sent message success!');
                            })
                            .fail(function (e) {
                                console.warn(e);
                            });
    });
    // Start the connection
    $.connection.hub.start();
    //A function to write events to the page
    function writeEvent(eventLog, logClass) {
        var now = new Date();
        var nowStr = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
        $('#messages').prepend('<li class="' + logClass + '"><b>' + nowStr + '</b> ' + eventLog + '.</li>');
    }
});

資源:

一個很酷的同步操作表格的示例(使用 jTable ):

http://www.codeproject.com/Articles/315938/Real-time-Asynchronous-Web-Pages-using-jTable-Sign

組通知示例:

http://www.codeproject.com/Articles/404662/SignalR-Group-Notifications


先寫到這里,以后在深度研究



向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI