Asp.NET MVC3 使用 SignalR 实现推送(接上)

2020-11-25 04:54

阅读:666

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 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 同样支持组进行推送。

soscw.com,搜素材

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("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";
}

Persistent Chat



消息记录: (你是:@ViewBag.ClientName):


    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(‘‘ + "系统消息" + ‘: ‘ + content, ‘event-message‘);
            }
            else {
                writeEvent(‘‘ + clientName + ‘ 对大家说: ‘ + 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(‘
  • ‘ + nowStr + ‘ ‘ + eventLog + ‘.
  • ‘); } });

    1,创建连接时,指定路径为 "/echo",该路径在服务器端的路由映射表被映射为 MyConnection,因而这个连接就被指向前面提供的 MyConnection。

    2,将 clientName 信息放入 message 中,并用 # 将 clientName 和消息内容连接成一个 msg。



    评论


    亲,登录后才可以留言!