我用一个非常基本的字符串测试这个信号。但是客户端没有触发服务器代码并且没有错误。我添加了[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改为此,输出为#34; undefine"但也没有错误
var haha = myHub.client.GetValueString; //在span中设置接收的serverTime以在浏览器中显示
答案 0 :(得分:2)
尝试给予此信息。另外,使用this作为参考
我已添加console.log
尝试,看看您在运行此代码时是否看到它。
(function () {
var myHub = $.connection.MyHub1;
myHub.client.GetValueString = function (serverTime) {
$("#newTime").html(serverTime);
};
$.connection.hub.logging = true;
$.connection.hub.start().done(function() {
console.log("hub is ready"); // tell me if you see the message in your console log
myHub.server.getstring() // note i wrote getstring with a small g, has to be.
});
}());
[HubName("MyHub1")]
public class MyHub1 : Hub
{
public void Hello()
{
Clients.All.hello();
}
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
);
}
}