Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send server message to connected clients with Signalr/PersistentConnection

Tags:

signalr

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?

like image 582
Campagnolo Avatar asked Oct 12 '25 23:10

Campagnolo


1 Answers

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());
    });
});
like image 63
davidfowl Avatar answered Oct 16 '25 07:10

davidfowl