.NET MVC5中使用SignalR2 Demo

1.打開工具|庫包管理器|包管理器控制檯,運行以下命令。這一步添加到項目的一套腳本文件和程序集引用,使signalr功能。

install-package Microsoft.AspNet.SignalR

2.在“解決方案資源管理器”中,展開腳本文件夾。注意,腳本庫signalr已添加到項目中。

Scripts folder

3.在解決方案資源管理器中,右鍵單擊該項目,選擇“添加|新文件夾,並添加一個新文件夾命名爲Hubs。

4.右鍵單擊集線器的文件夾,單擊“添加新項|,選擇Visual C # | Web | signalr節點,選擇SignalR Hub Class(V2),並創建一個新的Hub,叫ChatHub.cs。你會使用這個類作爲一個signalr服務器中心,把消息發送給所有客戶。

Create new hub

5.用下面的代碼替換chathub類代碼(下面的代碼意思是向所有的客戶端推送消息)

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}
6.創建一個新的OWIN Startup類稱爲startup.cs。


7.將startup.cs類中的代碼修改成如下代碼

using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}
8.創建控制器和視圖

9.將視圖中的代碼修改成如下(注:重點部分是JavaScript中的那一部分)

@{
    ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion">
    </ul>
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.--> 
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.  
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + htmlEncode(name) 
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}
如果想了解更多有關SignalR的相關內容,可以在官網上自己查閱
https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章