SignalR 2.2 users are experiencing a lack of message reception

I have developed a unique self-hosted SignalR application that is operating within the framework of a console application. To access the hubs within this application, I have implemented a wrapper class to avoid referencing the SignalR.Core assemblies directly in my ASP.NET project. This way, another C# class within my application is responsible for transmitting messages to connected clients.

Although I am able to interact with the PlanHub methods (Register and Unregister) directly from Javascript and reach breakpoints successfully, I encounter an issue when attempting to call client methods from a different class outside of the Hub. Even when using Clients.All to rule out concerns with Group registration, the message does not reach the intended clients. What could be causing this problem?

Upon examining the code, it appears that the line

Clients.All.updateStatus(planId, message);
is executed without errors, but no data is displayed on the client's console log.

Here are the key sections of the code:

PlanHub.cs

public class PlanHub : Hub
{
    private const string GroupPrefix = "PlanGroup_";

    public void Register(int companyId)
    {
        Groups.Add(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }

    public void Unregister(int companyId)
    {
        Groups.Remove(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }
}

PlanPublisher.cs

public class PlanPublisher
{
    private readonly static Lazy<PlanPublisher> _instance = new Lazy<PlanPublisher>(() => 
        new PlanPublisher(GlobalHost.ConnectionManager.GetHubContext<PlanHub>().Clients));
    private IHubConnectionContext<dynamic> Clients { get; set; }

    private PlanPublisher(IHubConnectionContext<dynamic> clients)
    {
        Clients = clients;
    }

    public static PlanPublisher Instance => _instance.Value;

    public void UpdateStatus(int planId, string message)
    {
        //Despite no exceptions being thrown, the message is not received by clients.
        //Even testing with Clients.All instead of Groups did not resolve the issue.
        Clients.All.updateStatus(planId, message);
    }
}

Calling code (from within another C# class)

PlanPublisher.Instance.UpdateStatus(plan.Id, $"Publishing started for {plan.Name}...");

Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
<script src="~/scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>
<script>
    $(document).ready(function() {
        $.connection.hub.url = "http://localhost:8080/signalr";

        var planMessagePublisher = $.connection.planHub;

        planMessagePublisher.client.updateStatus = function (planId, message) {
            console.log('Status: ' + planId + ' - ' + message);
        };

        $.connection.hub.start().done(function() {
            //The PlanHub.Register method executes successfully at this point.
            planMessagePublisher.server.register(@Model.CompanyId);

            // Also successfully logs the new connection ID to the console
            console.log('Now connected, connection ID=' + $.connection.hub.id);
        });
    });
</script>

JS Console Debugger Output

jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Auto detected cross domain url.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Client subscribed to hub 'planhub'.
...

Despite correct registration, the expected data does not propagate to the clients. The line

Clients.All.updateStatus(planId, message);
gets triggered multiple times, yet the additional logging data never reaches the console as anticipated.

UPDATE: Inquiring about a potential custom dependency resolver, the presented code resides isolated within its own project with minimal external components besides what has been showcased here. Although the section calling PlanPublisher.UpdateStatus() does feature a custom dependency resolver, this should not affect operations since it is segregated within its distinct assembly. Both PlanPublisher.cs and PlanHub.cs exist within a simplistic project solely linked to SignalR.Core and SignalR.SelfHost.

Answer №1

I attempted to simplify the example you provided (using SignalR 2.2.0)

Below is the Hub class:

public class PlanHub : Hub
{
    private const string GroupPrefix = "PlanGroup_";

    // hubcontext
    private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <PlanHub> ();

    public void Register(int companyId)
    {
        Groups.Add(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }

    public void Unregister(int companyId)
    {
        Groups.Remove(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }

    // static method using hub context
    public static void Static_UpdateStatus(int planId, string message)
    {
        hubContext.Clients.All.updateStatus(planId, message);
    }
}

As I do not have a backend and I am unsure about your approach, I set up a timer to call the method from C# every 10 seconds.

Code for calling and dummy timer:

    public void startTimer()
    {
        timer = new System.Timers.Timer();
        timer.Elapsed += new System.Timers.ElapsedEventHandler(ExecuteTimerJob);
        timer.Interval = 10000; // 10 sec
        timer.Start();
    }

    public static void ExecuteTimerJob(object source, System.Timers.ElapsedEventArgs e)
    {
        // this is the call from C#
        PlanHub.Static_UpdateStatus(123, "some message");
    }

Javascript code snippet:

$(function () {
    var planHub = $.connection.planHub;
    $.connection.hub.start().done(function () {
         console.debug('Connected to PlanHub...');
    })
    planHub.client.updateStatus = function (planId, message) {
        console.log("planId: " + planId);
        console.log("message: " + message);
    } 
});

Check the browser console for the result:

Answer №2

Give this a shot:

public void UpdateStatus(int id, string msg)
{
    var users = GlobalHost.ConnectionManager.GetHubContext<PlanHub>().Clients;
    users.All.updateStats(id, msg);
}

It seems that the issue lies in initializing PlanPublisher before the hub context (and Clients) are fully created.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reverting back to PDF using jQuery

I am currently utilizing jQuery to send JSON data back to the server, which in turn generates a PDF report. However, I am facing an issue where the PDF is not downloading despite specifying the necessary response header and including JavaScript as shown ...

Obtain Outcome from a Nested Function in Node.js

I'm grappling with the concept of manipulating the stack in JS and hoping this exercise will provide some clarity. Currently, I'm attempting to create a function that makes a SOAP XML call, parses the data, and returns it when called. While I c ...

How do I rearrange the order of a collection in Firestore using a reference that I already have?

Is there a method to maintain a reference of the same collection while altering the ordering using firestore? TLDR: I am looking to achieve similar functionality as demonstrated in: , but since my data is sourced from firestore, I am struggling to find th ...

Easily upload numerous files simultaneously with just one click of a button

This particular element, <asp:FileUpload ID="FileUploadEventosCasal" runat="server" /> is designed to upload a single file at a time when the button is clicked. I am interested in finding out how it would be possible to upload multiple files in a ...

Choosing2 - incorporate a style to a distinct choice

Let's talk about a select element I have: <select id="mySelect"> <option>Volvo</option> <option value="Cat" class="red">Cat</option> <option value="Dog" class="r ...

Troubleshooting Bootstrap 4 Modal in JavaScript and Vue: Uncaught ReferenceError: $ is not defined

I'm struggling to figure out how to trigger a Bootstrap 4 modal from my Vue 3 app using JavaScript. Whenever I try to launch the modal, I keep encountering this error message: $ is not defined at eval When looking for solutions, I noticed that most a ...

Encountering a NoSuchElementException when transitioning from frame[0] to window[1] in Firefox GeckoDriver using Selenium with Python

Encountered an issue with the Firefox GeckoDriver browser where I receive an error stating `element not found`. The problem arises when I navigate from window[1] to frame[0], back to window[1], and then attempt to click the close frame button. I prefer u ...

When you click the "Select All" button in a JavaScript dialogue box, all of the checkboxes on the main page will automatically be selected

After clicking a button on the main page to add a SKU, a new window opens with a search field, as shown in the image below. In this pop-up window, there is a "Check All" button that, when clicked, selects all checkboxes on both the pop-up window and the ma ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

Create custom AngularJS directives for validation and store them in a variable

Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

How to retrieve multiple checked values from checkboxes in Semantic UI React

Trying to enable users to select multiple checkboxes in react using semantic-ui-react. I am new to react. Here is my code: class ListHandOver extends React.Component { state = { data: {} } handleChange = (e, data) => { console.log( ...

Front-end displaying empty data fields on my webpage

I've been struggling to understand why my data isn't mapping correctly on these two components. I have attempted two debugging methods to analyze my code and have observed the data object for both the navigation and footer. Unable to comprehend ...

When using Javascript, you can expect to receive a modified structure that is different from

I am dealing with an array of objects that have the following structure: const data: [ { id: 21786162, label: "cBTC 2021-06-25 Put $50,000.00", active": true, type: "put", strike_price: 5000000, date_live: "2019-11- ...

Adjust the hue as you scroll

I've been searching for a solution to this issue, but I haven't been able to make it work. My goal is to have the page header change from a transparent background to a red background as the user starts scrolling down the page. $(window).on("s ...

Using the attribute data-ng-repeat along with the <option> tag allows for dynamic iteration and

Hello there, I am a beginner with AngularJS and I am struggling to understand how to create my <option> list. I would like my output to resemble the example in this fiddle: http://jsfiddle.net/XdpJv/ This is what my current code looks like: <se ...

Mastering the usage of AngularJS Directive controllerAs syntax with scope is key to developing

I have included my code below: // HTML <body> <h1>{{foo.name}}</h1> <my-directive></my-directive> </body> // Scripts app.directive('myDirective', function() { return { restrict: 'E', ...

You can only use the angularjs http function once

After browsing through similar forum posts, I was unable to find a solution to my issue. It could be due to my limited experience with JavaScript and Angular. Here's the problem: Desired Outcome: When I click a button, I want the data from the server ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

Unable to display content when the button is triggered

I am facing an issue with hiding a div (class="login-form") and displaying it only after clicking the Login button on my HTML page using jQuery. However, despite clicking the button, the login form does not appear. Can anyone help me understand why this ha ...