当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.NET MVC3 使用 SignalR 实现推送(接上)

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

2018年09月13日  | 移动技术网IT编程  | 我要评论

拿着烟斗的男孩歌词,三国好孩子无弹窗,家用监控摄像机

一,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 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("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>

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。


如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网