问题
I´m using SignalR/PersistentConnection, not the Hub.
I want to send a message from the server to client. I have the client id to send it, but how can I send a message from server to the client?
Like, when some event happens on server, we want send a notification to a particular user.
Any ideas?
回答1:
The github page shows how to do this using 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}");
}
}
Then on the client:
$(function () {
var connection = $.connection('echo');
connection.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
connection.start();
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
});
回答2:
May be the AddToGroup function in the helps in Server side
Put the clients in to different channels
public bool Join(string channel)
{
AddToGroup(channel.ToString()).Wait();
return true;
}
Then they Can send out message in different channel
public void Send(string channel, string message)
{
String id = this.Context.ClientId;
Clients[channel.ToString()].addMessage(message);
}
回答3:
using SignalR;
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
public class MyConnection : PersistentConnection
{
}
public class Notifier
{
public void Notify(string clientId, object data) {
MyConnection connection = (MyConnection) AspNetHost.DependencyResolver
.Resolve<IConnectionManager()
.GetConnection<MyConnection>();
connection.Send(clientId, data);
}
}
https://github.com/SignalR/SignalR/wiki/PersistentConnection
来源:https://stackoverflow.com/questions/7616983/send-server-message-to-connected-clients-with-signalr-persistentconnection