【发布时间】:2017-07-28 15:56:12
【问题描述】:
我正在用一个非常基本的字符串测试这个信号。但是客户端没有触发服务器代码并且没有错误。我在其中添加了[HubName("MyHub1")] 和[HubMethodName("GetValueString")],因为如果不是,javascript 将抱怨客户端未定义和找不到方法名。
在我添加这 2 个元后。没有错误,但服务器代码没有触发。请任何人帮忙。
客户端脚本
(function () {
// Defining a connection to the server hub.
debugger
var myHub = $.connection.MyHub1;
// Setting logging to true so that we can see whats happening in the browser console log. [OPTIONAL]
$.connection.hub.logging = true;
// Start the hub
$.connection.hub.start();
// This is the client method which is being called inside the MyHub constructor method every 3 seconds
myHub.client.GetValueString = function (serverTime) {
// Set the received serverTime in the span to show in browser
$("#newTime").html(serverTime);
};
}());
服务器脚本
[HubName("MyHub1")]
public class MyHub1 : Hub
{
public void Hello()
{
Clients.All.hello();
}
[HubMethodName("GetValueString")]
public void Getstring() {
var taskTimer = Task.Factory.StartNew(async () =>
{
while (true)
{
string timeNow = DateTime.Now.ToString();
//Sending the server time to all the connected clients on the client method ()
Clients.All.GetValueString("test");
//Delaying by 3 seconds.
await Task.Delay(3000);
}
}, TaskCreationOptions.LongRunning
);
}
}
更新 1 所以我把我的javascript改成这个,输出是“未定义”,但也没有错误
var haha = myHub.client.GetValueString; // 设置span中接收到的serverTime在浏览器中显示
【问题讨论】:
-
是什么激发了你的
Getstring()?也许做类似myHub.server.Getstring并删除[HubMethodName("GetValueString")] -
你也确定设置
app.MapSignalR(); -
仍然与顶部图片显示的错误相同。是的 o 在
public partial class Startupstartup.cs 处添加了 app.mappsignalr() -
同样的错误。删除 `[HubMethodName("GetValueString")]` 并将我的代码放入
.done后。我可以确认这一点,因为我在其中添加了一条 alert() 消息。
标签: javascript jquery asp.net-mvc signalr