2014-04-06 257 views
2

我一直在閱讀這篇文章從文檔:從服務器發送消息給客戶端,與SignalR

http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20-and-mvc-5

它說,我可以把來自客戶端的消息給服務器,像這樣:

$.connection.hub.start().done(function() { 
    $('#sendmessage').click(function() { 
     // Call the Send method on the hub. 
     chat.server.send($('#displayname').val(), $('#message').val()); 
     // Clear text box and reset focus for next comment. 
     $('#message').val('').focus(); 
    }); 
}); 

但是,如何從我的服務器發送消息到客戶端?

我第一次按照本教程http://www.codemag.com/Article/1210071其解釋說,我需要簡單地做到這一點:

SendMessage("Index action invoked."); 

隨着SendMessage()定義爲:

private void SendMessage(string message) 
{ 
    GlobalHost.ConnectionManager.GetHubContext<NotificationHub>().Clients.All.sendMessage(message); 
} 

但是,這是行不通的。在我的客戶端,我的錯誤是:

對象#有沒有方法「激活」

,我使用的客戶端代碼:

$.connection.hub.start(function() { 
    notificationHub.activate(function (response) { 
     /* 
     $("#target") 
     .find('ul') 
     .append($("<li></li>").html(response)); 
     */ 
     console.log(response); 
    }); 
}); 

所以,問題是,我怎樣才能從我的服務器發送一條簡單的消息到客戶端?

有人可以告訴我一個完整的例子,如何做到這一點?我從文檔中看到了股票行情的例子,但這很難理解/應用。

回答

3

據我瞭解您所呼叫稱爲這裏的sendMessage

private void SendMessage(string message) 
{ 
    GlobalHost.ConnectionManager.GetHubContext<NotificationHub>().Clients.All.sendMessage(message); 
} 

但是在客戶端的功能,我沒有看到一個定義在客戶端此功能。相反,您定義了一個名爲activate()的函數。另外,從我的工作代碼中,我已經定義了這樣的客戶端功能。

var hub = $.connection.notificationHub; 
    hub.client.sendMessage= function (data) { 
//some logic here 
} 
+0

不知道我的問題是什麼;但它現在正在工作。 – user1477388

相關問題