我有一個基于 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以警報訊息觸發。
讓我知道我錯在哪里。謝謝。
uj5u.com熱心網友回復:
在 hub.start 之前移動您的客戶端功能。在開始之前,您應該始終至少注冊一個函式。請參閱檔案中的注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/323214.html
