What is SignalR
ASP.NET SignalR is a new library for ASP.NET developers that simplifies the process of adding real-time web functionality to your applications. Real-time web functionality is the ability to have server-side code push content to connected clients instantly as it becomes available.
You may have heard of the HTML5 WebSocket API that enables efficient bidirectional communication between the browser and server. SignalR uses Websockets when it is supported by the browser and the server, and gracefully falls back to other techniques and technologies when it is not. Either way, your application code stays the same.
SignalR provides a simple ASP.NET API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), grouping connections, and authorization.
上面是http://www.asp.net/signalr 的介紹。
本人英文不太好,簡單翻譯一下就是:SignalR是一個新的類庫,它為ASP.NET開發者提供一個更簡單的途徑實現實時在線功能。SignalR可以實現服務端推送內容到客戶端的功能。SignalR通過HTML5的WebSocket來實現服務端跟瀏覽器的通信。如果瀏覽器不支持WebSocket 那么就用其他的技術來實現。不管哪種技術,最后都是同樣的效果。SignalR提供一組簡單的ASP.NET API去構建RPC功能。它可以通過服務端代碼去調用前端的javascript方法。SignalR同樣為連接管理,群組連接,權限等提供了API。
/*以下不是翻譯*/
SignalR非常微軟,它被微軟封裝的非常易用。不管是后台類庫,還是前端javascript都已經被你封裝好了。SignalR依賴JQuery。SignalR的實現原理類似WCF,使用javascript代理類來調用服務端的方法。廢話不多了上代碼吧。
后台:
新建一個空的MVC項目,添加一個最基本的View跟Controller這個就不廢話了。
在Global.asax的Start方法下面添加:
RouteTable.Routes.MapHubs();
初始化hub。
在在解決方案下新建文件夾:Hub。添加一個類叫ChatHub:
public class ChatHub : Microsoft.AspNet.SignalR.Hub { public void Send(string name, string message) { //send message to all pages Clients.All.SentMsgToPages(name, message); } }
啊,太簡單了。只有一個方法一行代碼。這個Send方法是提供給Client調用的。其中SentMsgToPages這是個動態方法,它表示前端的回調方法。也就是說Client調用Send方法把name跟message傳回server,然后server會回調所有的連接的client的SentMsgToPages方法,把name跟message提供到client。
前台:
@{ ViewBag.Title = "Index"; } <script src="~/Scripts/jquery.signalR-1.1.2.js"></script> <script src="~/signalr/hubs"></script> <script type="text/javascript"> var chat = $.connection.chatHub; chat.client.SentMsgToPages = function (name, message) { // Add the message to the page. $('#msgUl').append('<li><strong>' + name + '</strong>: ' + message + '</li>'); }; function sendMsg() { var userName = $("#userName").val(); if (!userName) { $(".alert").show(); return; } var msg = $('#messageBox').val(); if (msg) { chat.server.send(userName, msg); $('#messageBox').val('').focus(); } } $.connection.hub.start().done( function() { //設置按鈕事件 $("#btnSent").click( sendMsg ); $("#userName").focus( function () { $(".alert").hide(); } ); } ); $(document).ready( function () { //設置高度 var msgListH = window.innerHeight - 150; $(".messageList").height(msgListH); $('#messageBox').keypress( function(e) { var key = e.keyCode; if (key == 13) { sendMsg(); } } ); } ); </script> <h2>SignalR Chat Room</h2> <div style="width: 99%;margin: 4px" id="outBoard" > <div class="messageList" > <ul id="msgUl" class="unstyled"> </ul> </div> <div class="form-inline"> <input type="text" id="userName" placeholder="昵稱" class="input-mini" /> <input type="text" id="messageBox" class="input-xxlarge"/> <input type="submit" value="發送" class="btn btn-info" id="btnSent" /> </div> <div class="alert" style="display: none; width: 100px"> 必須輸入昵稱! </div> </div> 前台除去HTML其實也很簡單。最關鍵的也就3句話。
1 var chat = $.connection.chatHub;
客戶端跟服務端建立連接。
2 chat.client.SentMsgToPages = function (name, message) { };
這就是服務端回調客戶端的方法,給SentMsgToPages實現一個function表示如何處理返回值,這里當然是把message添加到聊天記錄列表里。
3 chat.server.send(userName, msg);
客戶端通過chat對象調用服務端的send方法,把數據傳回到服務器。
效果:
我們如此簡單的就實現了一個最基本的聊天室,SignalR當然還可以做網頁通知的推送,實時的進度條等等。這對ASP.NET程序員來說真是又一個神器。