Signalr connection problem

osyris 236 Reputation points
2021-09-07T01:01:56.117+00:00

every time i try to invoke the signalr connection i get a error message:

Unhandled Rejection (Error): Cannot send data if the connection is not in the 'Connected' State.

while the first thing i do is starting the connection i even get a comformation
in the console log saying: "SignalR is now connected"

reactjs code:

   useEffect(() => {

        const Connection = new HubConnectionBuilder()
        .withUrl('https://localhost:44332/chatHub')
        .withAutomaticReconnect()
        .build();
        setNewConnection(Connection)

        Connection.start().then(result => { console.log("SignalR is now connected")});

Connection.invoke("JoinGroup", "PrivateGroup");
 Connection.on("ReceiveMessage", (message) => {
        setTestName(message)})
        },[]); 

the back end:

    public async Task JoinGroup(string group)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, group);
        }

        public async Task SendMessageToGroup(string group, string message)
        {
            await Clients.Groups(group).SendAsync("ReceiveMessage", message);
        }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,161 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Jon Galloway 6 Reputation points Microsoft Employee
    2021-09-08T00:50:33.09+00:00

    Connection.invoke immediately returns a JavaScript promise, so I think you need to chain then() calls for anything that requires the connection to be started and available.

    While the code looks like it's invoking JoinGroup after the Connection has started, what actually happens is the Connection start method is called, a promise is returned while waiting for the connection to be established between client and server, and immediately after that the invoke method is called before the connection is fully started.

    Connection.start().then( result => { 
      console.log("SignalR is now connected")
    }).then( result => {
      Connection.invoke("JoinGroup", "PrivateGroup")
    });
    
    1 person found this answer helpful.
    0 comments No comments

  2. swapnil kamble 1 Reputation point
    2022-08-04T18:00:32.03+00:00

    I have single Page react application and it contained mostly the sibling component. Not sure how I can share the same single instant of hubconnection to multiple components and when some of the multiple component invoke some method then need to call signalR api and received data from server.
    Currently everything is working on localhost but I deployed on azure and getting the connection 404 error.

    Require guidance where I need to write the hubconnection so my all component with use the same connection instead of calling again or connecting again and again.

    0 comments No comments

  3. Bruce (SqlWork.com) 55,686 Reputation points
    2022-08-04T22:11:13.507+00:00

    you should move the connection logic to a module. that you import.

    import hub from "hubConnection";

    your component will need to subscribe and unsubscribe to messages, signal/r does not support this so your module should.

     useEffect(() => {   
        hub.on("ReceiveMessage", handler)   
        return function() {   
            hub.off("ReceiveMessage", handler);   
        }   
    }    
    

    I assume the hub code would subscribe to the messages, and have dispatch array for each.

    const conn = hub.getConnection(); // return the promise returned by start. you want a function to handle reconnect logic

    0 comments No comments