標籤:
在上節中,我們已經初步對 SignalR 進行了瞭解,這一節我們將做一個SignalR Demon,具體的步驟如下:
1. 建立一個 mvc 4 web 應用程式,並選擇 Basic
2. 建立一個 Home 控制器, 建立好後,目錄應該是這樣的:
3. 在項目中,滑鼠右鍵開啟 Nuget 程式管理組件,在 Nuget 程式管理組件中 輸入 signalr 這樣的字串進行搜尋,在搜尋結果中選中 Microsoft ASP.NET SignalR 這個項目,並點擊安裝
4. 在剛建立好的 Home 控制器 添加 一個 Index 的 Action ,並建立視圖,視圖的完整代碼如下:
<body> <div class="container"> <input type="text" id="message" id="message" /> <input type="button" id="sendmessage" value="Send" /> <input type="hidden" id="displayname" /> <ul id="discussion"></ul> </div> <script src="/Scripts/jquery-1.8.2.min.js"></script> <script src="/Scripts/jquery.signalR-2.1.2.min.js"></script> <script src="signalr/hubs"> </script> <script type="text/javascript"> $(function () { // 定義一個代理, 以引用 Hub var chat = $.connection.chatHub; //定義client端的javascript function,供server端hub,通過dynamic的方式,調用所有Clients的javascript function // 在對話方塊中輸入聊天者的姓名. $(‘#displayname‘).val(prompt(‘Enter your name:‘, ‘‘)); // 建立一個函數,以使 Hub 可以廣播訊息。 chat.client.broadcastMessage = function (name, message) { // 對字串進行html 編碼 var encodedName = $(‘#displayname‘).text(name).html(); var encodedMsg = $(‘#message‘).text(message).html(); //在頁面中追加並顯示聊天資訊 $(‘#discussion‘).append(‘•‘ + encodedName + ‘: ‘ + encodedMsg + ‘‘ + ‘</br>‘); }; // 設定訊息框的焦點格式. $(‘#message‘).focus(); // 與伺服器建立串連 $.connection.hub.start().done(function () { $(‘#sendmessage‘).click(function () { // 在Hub中調用 Send 方法 chat.server.send($(‘#displayname‘).val(), $(‘#message‘).val()); // 清空訊息輸入框 $(‘#message‘).val(‘‘).focus(); }); }); }); </script></body>
5. 在項目中建立 OWin Startup 啟動類, 並在Configuration(IAppBuilder app) 中添加以下 代碼:app.MapHubs(); 這段代碼的意義就是將 應用程式對應到 Hub 中去,這是在程式啟動運行時就會執行的。
6. 添加 ChatHub.cs 類,並建立 send(string name, string message) 方法,以便在用戶端能調用
public class ChatHub : Hub { public void Send(string name, string message) { Clients.All.broadcastMessage(name, message); } }
7. 對項目進行編譯,如果沒有錯的話,程式執行的結果應該是這樣的(以下是用fire fox瀏覽器):
在用IE 調試時,在項目中我們可以看到自動產生的一些呼叫指令碼,其中 hubs.js 就是個我們在用戶端所引用的 <script src="signalr/hubs"> </script>,它將會把伺服器中的方法推送到用戶端,以便在用戶端可以調用
Hubs.js 的完整代碼如下:
/*! * ASP.NET SignalR JavaScript Library v2.1.2 * http://signalr.net/ * * Copyright Microsoft Open Technologies, Inc. All rights reserved. * Licensed under the Apache 2.0 * https://github.com/SignalR/SignalR/blob/master/LICENSE.md * *//// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" />/// <reference path="jquery.signalR.js" />(function ($, window, undefined) { /// <param name="$" type="jQuery" /> "use strict"; if (typeof ($.signalR) !== "function") { throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js."); } var signalR = $.signalR; function makeProxyCallback(hub, callback) { return function () { // Call the client hub method callback.apply(hub, $.makeArray(arguments)); }; } function registerHubProxies(instance, shouldSubscribe) { var key, hub, memberKey, memberValue, subscriptionMethod; for (key in instance) { if (instance.hasOwnProperty(key)) { hub = instance[key]; if (!(hub.hubName)) { // Not a client hub continue; } if (shouldSubscribe) { // We want to subscribe to the hub events subscriptionMethod = hub.on; } else { // We want to unsubscribe from the hub events subscriptionMethod = hub.off; } // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe for (memberKey in hub.client) { if (hub.client.hasOwnProperty(memberKey)) { memberValue = hub.client[memberKey]; if (!$.isFunction(memberValue)) { // Not a client hub function continue; } subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue)); } } } } } $.hubConnection.prototype.createHubProxies = function () { var proxies = {}; this.starting(function () { // Register the hub proxies as subscribed // (instance, shouldSubscribe) registerHubProxies(proxies, true); this._registerSubscribedHubs(); }).disconnected(function () { // Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs. // (instance, shouldSubscribe) registerHubProxies(proxies, false); }); proxies[‘chatHub‘] = this.createHubProxy(‘chatHub‘); proxies[‘chatHub‘].client = { }; proxies[‘chatHub‘].server = { send: function (name, message) { return proxies[‘chatHub‘].invoke.apply(proxies[‘chatHub‘], $.merge(["Send"], $.makeArray(arguments))); } }; return proxies; }; signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false }); $.extend(signalR, signalR.hub.createHubProxies());}(window.jQuery, window));
好了,非常感謝你的閱讀,如果有什麼好的想法,歡迎與我交流。
源碼:下載源碼
SignalR + Mvc 4 web 應用程式