Asp.NET MVC3 使用 SignalR 實現推送(接上)

來源:互聯網
上載者:User

標籤:c#   asp.net   

一,Persistent Connection 樣本教程1,實現伺服器端代碼
1),編寫伺服器 PersistentConnection 代碼

項目中 SignalR 目錄下建立 PersistentConnection.cs 檔案

using System;using System.Collections.Generic;using System.Threading.Tasks;using SignalR;namespace SignalTutorial.SignalR{    public class MyConnection : PersistentConnection    {        protected override Task OnConnectedAsync(IRequest request, string connectionId)        {            return Connection.Broadcast("Connection " + connectionId + " connected");        }        protected override Task OnReconnectedAsync(IRequest request, IEnumerable<string> groups, string clientId)        {            return Connection.Broadcast("Client " + clientId + " re-connected");        }        protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)        {            var info = data + ". ConnectionId is [" + connectionId + "]";            // return Connection.Send(connectionId, info);               // Broadcast data to all clients            return Connection.Broadcast(info);           }        protected override Task OnDisconnectAsync(string connectionId)        {            return Connection.Broadcast("Connection " + connectionId + " disconncted");        }        protected override Task OnErrorAsync(Exception error)        {            return Connection.Broadcast("Error ocurred " + error);        }    }}

1,MyConnection 繼承自 PersistentConnection,這樣我們就能在用戶端串連,重串連,中斷連線,發送訊息以及串連出錯的情況下進行相關的處理。從下面的 PersistentConnection 介面中可以看到,PersistentConnection 同樣支援組進行推送。


2,推送訊息由 PersistentConnection 的屬性 Connection 來提供,它繼承自 IConnection 介面,該介面提供兩個函數來實現對特定用戶端的推送和廣播功能。

System.Threading.Tasks.Task Send(string signal, object value)
System.Threading.Tasks.Task Broadcast(object value)

2),配置訪問路由

為了支援用戶端訪問,我們將對路由表中進行配置。開啟 Global.asax.cs ,修改 Application_Start() 函數如下:

protected void Application_Start(){    AreaRegistration.RegisterAllAreas();    RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");    RegisterGlobalFilters(GlobalFilters.Filters);    RegisterRoutes(RouteTable.Routes);    // Make connections wait 50s maximum for any response. After    // 50s are up, trigger a timeout command and make the client reconnect.    GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(50);    //DisconnectTimeout     //HeartBeatInterval     //KeepAlive }

在上面的代碼中,我將 echo 及其子路徑的訪問映射到 MyConnection 上,並設定連線逾時時間為 50 s。在這裡還可以設定其他的一些參數,如斷連逾時時間,心跳間隔等。

2,實現用戶端代碼
@model dynamic@{    ViewBag.Title = "title";}<script src="@Url.Content("~/Scripts/persistent.js")" type="text/javascript"></script><h2>Persistent Chat</h2><div>    <input type="text" id="Placeholder" value="@ViewBag.ClientName" hidden="true"/>    <input type="text" id="msg" />    <input type="button" id="broadcast" value="廣播" />    <br />    <br />        <h3>        訊息記錄: (你是:<span id="MyClientName">@ViewBag.ClientName</span>):    </h3>    <ul id="messages">    </ul></div>

2),編寫 Javascript

向 Scripts 目錄添加新的 Javescript 指令碼:persistent.js。其內容如下:

$(function () {    var myClientName = $(‘#Placeholder‘).val();    var connection = $.connection(‘/echo‘);    connection.received(function (data) {        var msg = new String(data);        var index = msg.indexOf("#");        var clientName = msg.substring(0, index);        var content = msg.substring(index + 1);        if (clientName == null || clientName == "") {            writeEvent(‘<b>‘ + "系統訊息" + ‘</b>: ‘ + content, ‘event-message‘);        }        else {            writeEvent(‘<b>‘ + clientName + ‘</b> 對大家說: ‘ + content, ‘event-message‘);        }    });    connection.start();    $("#broadcast").click(function () {        var msg = myClientName + "#" + $(‘#msg‘).val();        connection.send(msg);    });    //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>‘);    }});

1,建立串連時,指定路徑為 "/echo",該路徑在伺服器端的路由映射表被映射為 MyConnection,因而這個串連就被指向前面提供的 MyConnection。

2,將 clientName 資訊放入 message 中,並用 # 將 clientName 和訊息內容串連成一個 msg。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.