服务器发送新映像后间隔更新客户端映像

时间:2014-09-07 23:25:25

标签: javascript html asp.net-mvc signalr

在我的ASP.NET MVC应用程序中,服务器在5秒后向所有客户端广播图像URL 我正在使用SignalR从服务器发送图像URL,调用Javascript函数。

在Javascript函数中,我使用以下代码自动刷新<img>元素来更新src属性,但是虽然它正在更新我的src但我无法在浏览器上看到。

// Defining a connection to the server hub.
var myHub = $.connection.myHub;
// 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.SendServerImageUrl = function (serverImageUrl) {
var N = 5;
// Function that refreshes image
function refresh(imageId, imageSrc) {
    var image = document.getElementById(imageId);
    var timestamp = new Date().getTime();
    image.src = imageSrc + '?' + timestamp;
};
// Refresh image every N seconds
setTimeout(function () {
    refresh('SampleImage', serverImageUrl);
}, N * 1000);

我的HTML文件仅包含以下代码:

<img id="SampleImage"> 

后端C#代码

 public class MyHub : Hub
     {
         public MyHub()
         {
         // Create a Long running task to do an infinite loop which will keep sending the server time
        // to the clients every 5 seconds.
        var taskTimer = Task.Factory.StartNew(async () =>
            {
                while(true)
                {

                    Random rnd = new Random();
                    int number = rnd.Next(1,10);
                    string str = "~/Images/Sample";


                    Clients.All.SendServerImageUrl(str+Convert.ToString(number)+".jpg");

                    //Delaying by 5 seconds.
                    await Task.Delay(5000);
                }
            }, TaskCreationOptions.LongRunning
            );
    }

}

1 个答案:

答案 0 :(得分:0)

尝试更改回调中的大小写:

myHub.client.sendServerImageUrl = ...;

Clients.All.sendServerImageUrl(...);

不需要轮询,所以在客户端上摆脱setTimeout()

密切关注控制台并确保HTTP请求正常运行。