使用SignalR将消息从后台代码推送到客户端

本文关键字:客户端 代码 后台 SignalR 消息 使用 | 更新日期: 2023-09-27 18:08:25

我正在从excel电子表格中导入记录。我想用每条记录的进度更新客户端屏幕。我被告知SignalR是未来的发展方向。

我从ChatHub示例开始,并对其进行了一些简化。

编辑… 似乎broadcastMessage函数正在工作,但行为奇怪。下面是一段简短的视频:https://www.youtube.com/watch?v=wRqiyaQ2hD0

ASPX页

<form id="form2" runat="server">
    <ul id="progressReport"></ul>
    <asp:Button Text="Push message" ID="btn" OnClick="btn_Click" runat="server" />
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.8.2.min.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub. 
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message. 
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page. 
                $('#progressReport').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Start the connection.
            $.connection.hub.start().done(function () {
                chat.server.send($('#displayname').val(), $('#message').val());
            });
        });
    </script>
</form>

ASPX.CS

using SignalRChat;
using System;
namespace SignalR_Test
{
    public partial class form2 : System.Web.UI.Page
    {
        protected void btn_Click(object sender, EventArgs e)
        {
            ChatHub ch = new ChatHub();
            for ( int i = 0; i <= 10; i++)
            {
                ch.Send("Code Behind", i +" has been imported");
            }
        }
    }
}

ChatHub.CS

using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            // Call the broadcastMessage method to update clients.
            context.Clients.All.broadcastMessage(name, message);
        }
    }
}

使用SignalR将消息从后台代码推送到客户端

尝试将此添加到您的aspx页面并检查它是否在javascript控制台记录调用:

$.connection.hub.logging = true;
$.connection.hub.start();

你的类被称为ChatHub,你正在做一个connection.chatHub在你的客户端(注意小写的c vs大写)。尝试在Hub类中添加HubName属性:

[HubName("chatHub")]
public class ChatHub : Hub

同样,尝试添加~/到你的脚本src:

<script src="~/signalr/hubs"></script>

您是否缺少所需的Startup课程?

JS脚本版本(jquery.signalR-2.0.3.min.js, jquery-1.8.2.min.js)是否与"scripts"目录下的脚本匹配?