【发布时间】:2014-02-07 17:19:30
【问题描述】:
我有一个 Windows 服务的工作实现,它充当 SignalR 客户端,向 ASP.NET MVC(服务器)中集线器上的方法发送消息。我只需要知道如何使用 MVC 在视图或其他内容中显示我收到的字符串。
我在设置 hubConnection 并调用“Hello”方法的 Windows 服务中有以下客户端代码:
protected override async void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
try
{
var hubConnection = new HubConnection("http://localhost/AlphaFrontEndService/signalr", useDefaultUrl: false);
IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");
await hubConnection.Start();
// Invoke method on hub
await alphaProxy.Invoke("Hello", "Message from Service");
}
catch (Exception ex)
{
eventLog1.WriteEntry(ex.Message);
}
}
当我启动服务时,它会使用这个集线器和方法调用我的 MVC 应用程序:
public class AlphaHub : Hub
{
public void Hello(string message)
{
// We got the string from the Windows Service
// using SignalR. Now need to send to the clients
Clients.All.addNewMesssageToPage(message);
}
}
我在 HomeController 上设置了一个方法:
public ActionResult Messaging()
{
return View();
}
然后是消息视图:
@{
ViewBag.Title = "Messaging";
}
<h2>Messaging</h2>
<ul id="messages"></ul>
@section scripts
{
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function() {
var alpha = $.connection.alphaHub;
// Create a function that the hub can call back to display messages
alpha.client.addNewMessageToPage = function (message) {
// Add the message to the page.
$('<li />').text(message).appendTo('#messages');
};
$.connection.hub.start();
});
</script>
}
它不会在 /Home/Messaging 更新浏览器
【问题讨论】:
-
你希望这个视图如何显示?在用户的浏览器中?
-
如果您要问的话,我不想使用 JavaScript。我已经有了 SignalR 部分,所以我不想使用 SignalR JavaScript 库。我只是想最终在用户的浏览器中使用 MVC 视图。
-
SignalR 无法与没有 JavaScript 的浏览器通信。如果没有 JavaScript 客户端,你能做的最好的事情就是让集线器将传入的消息保存在服务器上,并在下次有人从 MVC 请求页面时显示它们。但这违背了 SignalR 的目的。如果您不进行实时消息传递,则可能不需要 SignalR。
-
我正在做从 Windows 服务到 MVC 应用程序的实时消息传递。我想我需要使用 JavaScript 客户端将结果实时发送到客户端。您能否在答案中显示一些代码来使用我的 AlphaHub 执行此操作?
-
哦,我已经在 Startup 类中设置 SignalR 为 Windows 服务客户端映射:app.MapSignalR("/signalr", new HubConfiguration());
标签: asp.net-mvc signalr