从服务器到客户端的SignalR通知 [英] SignalR notification from server to client
问题描述
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
我想要的是一个按钮,其onClick方法正在服务器上运行.一次,我单击此按钮,必须将通知(字符串消息)发送给所有客户端.
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.
我的Hub类是
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??
我在客户端网页上通知的JS就是这样
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 + "'");
};
推荐答案
您需要在按钮单击功能中调用 broadcastNotification
,如下所示:
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");
此外,您需要通过添加 $.connection.hub.start()
来启动集线器,您的JS文件应类似于:
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>
这篇关于从服务器到客户端的SignalR通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!