![](/img/trans.png)
[英]Is it possible to synchronously call Signalr server side method from javascript client?
[英]SignalR client side method not firing on from server side button click
我有一個基於 Visual Studio 2019 的 SignalR 應用程序,客戶端連接到服務器。
當頁面加載並連接到正在運行的服務器時,將調用以下 javascript 函數,並使用成功的 connectionid。
function Connect() {
$.connection.hub.url = url;
stockTickerHubProxy = $.connection.mobileStockTickerHub;
if (stockTickerHubProxy) {
$.connection.hub.start().done(function () {
console.log("Connected...");
connectionId = $.connection.hub.id;
console.log(connectionId)
stockTickerHubProxy.server.setUserName(code);
})
.fail(function () {
alert("Can't connect");
})
;
stockTickerHubProxy.client.addMessage = function (name, message) {
console.log(name + ":" + message);
}
stockTickerHubProxy.client.showtradenotification = function (msg) {
alert(msg)
}
$.connection.hub.disconnected(function () {
console.log("Server disconnected.");
});
$.connection.hub.reconnecting(function () {
console.log("Server reconnecting...");
});
$.connection.hub.reconnected(function () {
console.log("Server reconnected...");
Connect();
});
$.connection.hub.error(function (error) {
console.log('SignalR error: ' + error)
});
}
}
在服務器上,我正在執行以下測試代碼來檢查在 javascript html 頁面中運行的函數。 以下是代碼。
private async void button1_ClickAsync(object sender, EventArgs e)
{
mhubContext = GlobalHost.ConnectionManager.GetHubContext<MobileStockTickerHub>();
await mhubContext.Clients.All.showtradenotification("Hello");
}
以下是中心類MobileStockTickerHub
public class MobileStockTickerHub : Hub
{
//Called when a client is connected
public override Task OnConnected()
{
_users.TryAdd(Context.ConnectionId, Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string username;
_users.TryRemove(Context.ConnectionId, out username);
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
_users.TryAdd(Context.ConnectionId, Context.ConnectionId);
return base.OnReconnected();
}
public string SetUserName(string userName)
{
_users[Context.ConnectionId] = userName;
return "Received ping from " + userName;
}
}
同樣,當button1_ClickAsync
被觸發時,網頁上沒有任何活動,應該會觸發帶有警報消息的showtradenotification
。
讓我知道我錯在哪里。 謝謝。
在 hub.start 之前移動您的客戶端功能。 在開始之前,您應該始終至少注冊一個函數。 請參閱文檔中的注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.