Asp.NET MVC3 使用 SignalR 实现推(持续)

一,Persistent Connection 演示示例教程

1。实现server端代码


1),编写server 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,这样我们就能在client连接,重连接,断开连接,发送消息以及连接出错的情况下进行相关的处理。从以下的 PersistentConnection 接口中能够看到,PersistentConnection 相同支持组进行推送。


2。推送消息由 PersistentConnection 的属性 Connection 来提供。它继承自 IConnection 接口。该接口提供两个函数来实现对特定client的推送和广播功能。

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

2)。配置訪问路由

为了支持client訪问,我们将对路由表中进行配置。打开 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。实现client代码

@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"。该路径在server端的路由映射表被映射为 MyConnection。因而这个连接就被指向前面提供 MyConnection。

2,将 clientName 信息成 message 在,同 # 将 clientName 和消息内容被连接到一个 msg。


原文地址:https://www.cnblogs.com/bhlsheji/p/4570862.html