javascript - 我的 javascript SignalR Azure 连接未触发事件

标签 javascript azure signalr owin .net-4.8

我已在 Azure 服务器和客户端之间建立了 SignalR 连接。连接已创建,但客户端上未触发事件。

我可以从客户端向服务器发送一条消息,并且我已确认服务器收到了该消息。但是,客户端上的事件不会被触发。我什至尝试从客户端调用客户端上的事件(您可以在下面的客户端代码中看到“sendMessage”),但这不会触发。

我读到,在调用 connection.start 之前,至少需要将一个事件附加到集线器代理;所以已经这样做了 - 但事件仍然不起作用。

我的客户端代码是:

"use strict";

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

var connection = $.hubConnection();
connection.url = 'https://localhost:44444/signalr/hubs';
var reportHubProxy = connection.createHubProxy("reportHub");

reportHubProxy.on("receiveMessage", function (user, message)
{
    console.log(user + ' ' + message + ' receiveMessage - connection ID=' + connection.id);
    var li = document.createElement("li");
    document.getElementById("messagesList").appendChild(li);
    // We can assign user-supplied strings to an element's textContent because it
    // is not interpreted as markup. If you're assigning in any other way, you 
    // should be aware of possible script injection concerns.
    li.textContent = "${user} says ${message}";
});

reportHubProxy.on("sendMessage", function (user, message)
{
    console.log(user + ' ' + message);
});

connection.start()
    .done(function ()
    {
        document.getElementById("sendButton").disabled = false;
        console.log('Now connected, connection ID=' + connection.id);
        document.getElementById("sendButton").addEventListener("click", function (event)
        {
            var user = document.getElementById("userInput").value;
            var message = document.getElementById("messageInput").value;
            console.log(user + ' ' + message + ' sent - connection ID=' + connection.id);
            reportHubProxy.invoke("sendMessage", user, message)
                .then(function (err)
                {
                    return console.log(user + ' ' + message + ' complete - connection ID=' + connection.id);
                })
                .catch(function (err)
                {
                    return console.error(err.toString());
                });
            //event.preventDefault();
        });
    })
    .fail(function ()
    {
        console.log('Could not Connect!');
    });

我看到来自connection.start的控制台日志,但看不到来自receiveMessage或sendMessage的控制台日志。

我的服务器端代码很简单并且似乎工作正常:

Imports Microsoft.AspNet.SignalR
Imports System.Threading.Tasks

Public Class ReportHub
    Inherits Hub

    Public Async Function SendMessage(ByVal user As String, ByVal message As String) As Task
        Await Clients.All.SendAsync("ReceiveMessage", user, message)
    End Function
End Class
Imports Owin
Imports Microsoft.Owin
Imports Microsoft.Owin.Hosting
Imports System.Web.Http
Imports System.IO
Imports Microsoft.AspNet.SignalR

Public Class Startup

    Public Sub Configuration(ByVal app As IAppBuilder)
        app.MapSignalR()
    End Sub

End Class

我已在已安装文件 jquery.signalR-2.4.2.js 的客户端上安装了 Microsoft.AspNet.SignalR.js。

最佳答案

我现在通过做两件事来完成这项工作:

  1. 将代码包装在
$(function (){ }):
  • 切换到使用生成的代理,如下所述:https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client
  • 我首先尝试执行 1.,但这本身不起作用。

    所以我的客户端代码现在看起来像这样:

    $(function ()
    {
        "use strict";
    
        //Disable send button until connection is established
        document.getElementById("sendButton").disabled = true;
    
        $.connection.hub.url = 'https://localhost:44444/signalr/hubs';
        var reportHubProxy = $.connection.reportHub;
        reportHubProxy.client.receiveMessage = function (user, message)
        {
            console.log(user + ' ' + message + ' received - connection ID=' + $.connection.hub.id);
            var li = document.createElement("li");
            document.getElementById("messagesList").appendChild(li);
            // We can assign user-supplied strings to an element's textContent because it
            // is not interpreted as markup. If you're assigning in any other way, you 
            // should be aware of possible script injection concerns.
            li.textContent = user + ' says ' + message;
        };
    
        //This does not get called
        reportHubProxy.on("sendMessage", function (user, message)
        {
            console.log(user + ' ' + message);
        });
    
        $.connection.hub.start()
            .done(function ()
            {
                document.getElementById("sendButton").disabled = false;
                console.log('Now connected, connection ID=' + $.connection.hub.id);
                // Wire up Send button to call NewreportMessage on the server.
                $('#sendButton').click(function ()
                {
                    var user = document.getElementById("userInput").value;
                    var message = document.getElementById("messageInput").value;
                    console.log(user + ' ' + message + ' sent - connection ID=' + $.connection.hub.id);
                    reportHubProxy.server.sendMessage(user, message)
                        .then(function (err)
                        {
                            return console.log(user + ' ' + message + ' complete - connection ID=' + $.connection.hub.id);
                        })
                        .catch(function (err)
                        {
                            return console.error(err.toString());
                        });
                    //$('#message').val('').focus();
                });
            })
            .fail(function ()
            {
                console.log('Could not Connect!');
            });
    });
    

    我之前尝试过使用生成的代理,但没有注意到重要的说明:

    As you can see from the examples, when you use the generated proxy, $.connection.hub refers to the connection object. This is the same object that you get by calling $.hubConnection() when you aren't using the generated proxy.

    另请注意,创建集线器代理时,您使用 $.connection.reportHub(不带 .hub)。

    我仍然无法触发客户端“on”事件 - 因此,如果您知道如何解决该问题,请告诉我。

    我将服务器中心更改为:

    mports Microsoft.AspNet.SignalR
    Imports System.Threading.Tasks
    
    Public Class ReportHub
        Inherits Hub
    
        Public Sub SendMessage(ByVal user As String, ByVal message As String)
            Clients.All.receiveMessage(user, message)
        End Sub
    End Class
    

    现在我只需要弄清楚如何将其集成到我的项目中,设置 token 处理等。

    关于javascript - 我的 javascript SignalR Azure 连接未触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69453270/

    相关文章:

    javascript - 如果 React 组件的 props 更新但值没有改变,它会重新渲染吗?

    javascript - 刷新时滚动到页面顶部

    javascript - 如何使用 new 构造函数为 json 中的每个节点创建一个实例?

    c# - Application Insights 和失败的请求响应代码

    angular - 访问 XMLHttpRequest 已被阻止源 ASP.NET CORE 2.2.0/Angular 8/signalr1.0.0 [(CORS Policy-Access-Control-Allow-Origin) failed]

    javascript - Backbone.js和localStorage插件集合和模型的关系——基于官方 'todo'示例

    azure - 如何使用应用服务对 Azure 函数应用进行身份验证/授权?

    azure - Terraform - 将 for_each 与元组内的字符串列表一起使用

    signalr - 角度 : Unable to pass API url in SignalR HubConnection

    java - Android SignalR java 客户端 : Not receiving all the SignalR messages on the HubConnection