【发布时间】:2014-06-13 21:38:00
【问题描述】:
我正在从 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>: ' + 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);
}
}
}
【问题讨论】: