您好,登錄后才能下訂單哦!
所需環境:SignalR運行在.NET 4.5平臺上,這里演示時采用ASP.NET MVC 3;
一.簡介
ASP .NET SignalR 是一個ASP .NET 下的類庫,可以在ASP .NET 的Web項目中實現實時通信。
二.原理
其實現原理跟WCF或Remoting相似,均為使用遠程代理來實現。實現接口有2種分別是PersistentConnection 和 Hubs,其中PersistentConnection 是實現長時間js輪循的,Hub是用來解決實時信息交換問題,其利用js動態載入方法實現,客戶端與服務器端全部使用json來交換數據。
三.Demo創建
1.打開NuGet 安裝 Microsoft ASP.NET SignalR
2.實現
a).實現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("數據是:{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="發送" /> <input type="button" id="btnStop" value="停止" /> <ul id="messages"> </ul>
執行效果如下:
可在
protected
override
Task OnReceivedAsync(
string
clientId,
string
data)
方法中進行消息的監視。
b).實現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(); }
對應的視圖代碼為:
@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所對應的內容如下:
$(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
先寫到這里,以后在深度研究
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。