使用SignalR/PersistentConnection将服务器消息发送到连接的客户端 [英] Send server message to connected clients with Signalr/PersistentConnection

查看:16
本文介绍了使用SignalR/PersistentConnection将服务器消息发送到连接的客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是SignalR/PersistentConnection,而不是集线器。

我要从服务器向客户端发送一条消息。我有要发送的客户端ID,但是如何将消息从服务器发送到客户端?

例如,当服务器上发生某些事件时,我们希望向特定用户发送通知。

有什么想法吗?

推荐答案

github页显示了如何使用PersistentConnections执行此操作。

public class MyConnection : PersistentConnection {
    protected override Task OnReceivedAsync(string clientId, string data) {
        // Broadcast data to all clients
        return Connection.Broadcast(data);
    }
}

Global.asax

using System;
using System.Web.Routing;
using SignalR.Routing;

public class Global : System.Web.HttpApplication {
    protected void Application_Start(object sender, EventArgs e) {
        // Register the route for chat
        RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");
    }
}

然后在客户端:

$(function () {
    var connection = $.connection('echo');

    connection.received(function (data) {
        $('#messages').append('<li>' + data + '</li>');
    });

    connection.start();

    $("#broadcast").click(function () {
        connection.send($('#msg').val());
    });
});

这篇关于使用SignalR/PersistentConnection将服务器消息发送到连接的客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆