Reputation: 1711
I want to push a notification from my server to client. I've tried the chat tutorial found here but this just sends chat messages from one client to client
What I want is a button whose onClick method is running at server. Once, I click this button, notifications (a string message) must be sent to all clients.
My Hub class is
public class NotificationsHub : Hub
{
public void SendNotification(string author, string message)
{
Clients.All.broadcastNotification(author, message);
}
}
and in the button click, I try this
var context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.SendNotification("Admin", "stop the chat");
But still, I'm not able to notify the clients. Nothing is happening. What am I doing wrong??
My JS at client web page to notify is like this
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.notificationsHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.broadcastNotification = function (name, message) {
alert(name + " says '" + message + "'");
};
Upvotes: 0
Views: 6515
Reputation: 15188
You need to call broadcastNotification
in your button click function, like below:
var context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.broadcastNotification("Admin", "stop the chat");
Also, you need to start the hub by adding $.connection.hub.start()
, your JS file should be like:
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.signalR-2.0.1.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var notifications = $.connection.notificationsHub;
notifications.client.broadcastNotification = function (name, message) {
alert(name + " says '" + message + "'");
$.connection.hub.start();
};
</script>
Upvotes: 4