1. 程式人生 > >使用 ASP.NET SignalR實現實時通訊

使用 ASP.NET SignalR實現實時通訊

ASP.NET SignalR 是為 ASP.NET 開發人員提供的一個庫,可以簡化開發人員將實時 Web 功能新增到應用程式的過程。實時 Web 功能是指這樣一種功能:當所連線的客戶端變得可用時伺服器程式碼可以立即向其推送內容,而不是讓伺服器等待客戶端請求新的資料。

  官網:http://signalr.net/

  下載:install-package Microsoft.AspNet.SignalR

  

  本節將簡單快速介紹

實現原理

  1. 如果瀏覽器<=Internet Explorer 8,用長輪詢的方式
  2. 如果配置中指定了使用jsonp,則會使用長輪詢的方式
  3. 如何需要建立跨域連線,將會如使用WebSocket,如果一下條件滿足的話(否則用長輪詢)
    1. 客戶端支援WebSocket
    2. 服務端支援WebSocket
    3. 客戶端支援Cross-Origin Resource Sharing

基於SignalR(SR)的實現原理,所以SR在客戶端瀏覽器IE8以上基本都是完全相容的。可以說完全支援jQuery 1.6.4的瀏覽器就能支援SignalR。

Hello World

建立空的Asp.Net專案

安裝

  install-package Microsoft.AspNet.SignalR

  install-package bootstrap

新增一個集線器類

複製程式碼
public class ChatHub : Hub
{
    public void Send(string name, string
message) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(name, message); } }
複製程式碼

新增一個OWIN Startup類

複製程式碼
[assembly: OwinStartup(typeof(SignalRChart.Startup))]
 
namespace SignalRChart
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            
// 有關如何配置應用程式的詳細資訊,請訪問 http://go.microsoft.com/fwlink/?LinkID=316888 app.MapSignalR(); } } }
複製程式碼

新增一個index.html

1.匯入js

複製程式碼
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
複製程式碼

2.hub

複製程式碼
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
 
// Call the Send method on the hub.
chat.server.send(name, message);
 
 // Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
}
複製程式碼

快速分析

Hub程式碼

Client程式碼

 

1.傳送給所有客戶端
Clients.All.onMsg

2.傳送給單一客戶端
Clients.Client(_clientID).onMsg 

3.傳送給其他客戶端
Clients.AllExcept(_clientID).onMsg
Clients.Ohther.onMsg

4.傳送給當前客戶端
Clients.Caller.onMsg

注意事項

In ASP.NET MVC 4 you can do the following:

<script src="~/signalr/hubs"></script>

If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:

<script src="@Url.Content("~/signalr/hubs")"></script>

Chat.cshtml頁面程式碼:

@{
    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" />
    <div id="discussion" style="overflow: auto; width: 400px; height: 200px; border: 1px solid #999; ">
    </div>
</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.0.3.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.
                var div = document.getElementById('discussion');
                div.innerHTML = div.innerHTML + '<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</li>';
                div.scrollTop = div.scrollHeight;
            };
            // 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>
}