所以我试图在项目中实现SignalR,我的代码如下:
MtHub.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace HaldanMT
{
public class MtHub : Hub
{
public void RemoveResource(string message)
{
Clients.All.RemoveResource(message);
}
}
}
custom.js:
$(document).ready(function () {
$.connection.mtHub.client.removeResource = function (message) { // This is the client listener that will fire once the server invokes the message. This is not taking place
console.log("finished");
RemoveResource(message); // Function to be invoked once the signalR message has been received from the server
}
});
function RemoveSelf(message){
$.connection.hub.start()
.done(function () {
console.log("Fire SignalR");
$.connection.mtHub.server.removeResource(message); // Invoke the SingalR server function that would in turn invoke the client listening function
})
.fail(function () {
console.log("Error With SignalR");
});
}
function RemoveResource(message){
alert(message); // Display message
}
HTML:
<button onclick="RemoveSelf('This is a message');">Click Me</button>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.1.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script src="~/Scripts/custom.js" type="text/javascript"></script>
现在......在按钮单击事件上触发了正确的函数,但是没有调用对客户端的响应。如果我将SignalR调用js函数放在文件准备就绪的按钮的onclick事件包围,它就可以正常工作。但我需要在函数RemoveSelf(message)
中触发signalR调用js函数,因为其他事情需要在我的代码中进行。
所以我的问题是:SignalR是否需要通过元素侦听器调用服务器端代码,而不是在标准函数内调用。我发现的大多数示例都使用基于jquery事件的侦听器而不是传统函数。
提前谢谢。
答案 0 :(得分:2)
The SignalR Server side code does not require invocation via element listener, but that's kind of a double-edge sword because JavaScript essentially works off events.
Your code should work exactly as it sits, but here's my code exactly and it works 100% (I don't see really many differences between our code. Could just be a typo somewhere) :
[HubName("mtHub")]
public class MtHub : Hub
{
public void RemoveResource()
{
Clients.All.RemoveResource("yo");
}
}
$(function() {
$.connection.mtHub.client.removeResource = function () {
alert("see it worked");
}
});
var CallIt = function() {
var connection = $.connection.mtHub;
$.connection.hub.start().done(function () {
alert("connected");
connection.server.removeResource().done(function () {
console.log("hi");
});
});
}
<h2 onclick="CallIt()">Fun Stuff</h2>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/jquery.signalR-2.2.1.js"></script>
<script src="~/signalr/hubs"></script>
<script src="~/Scripts/client-side.js"></script>
If this doesn't work, can you let me know what errors you get?
答案 1 :(得分:0)
您的客户端方法的方法名称包含错误,您使用的是“RemoveResource”,它们应该是“removeResource”
这是不正确的:
function RemoveResource(message){
alert(message); // Display message
}
这应解决问题:
function removeResource(message){
alert(message); // Display message
}