Search code examples
asp.net-coreasp.net-core-signalr

Calling Clients.Others.SendAsync disconnects recipient


To test my app, I open multiple connections to a signalr hub running on localhost in my browser. They connect fine up until one client calls the Host function at which point the other clients throw an error:

[2020-04-23T18:17:18.374Z] Debug: HubConnection connected successfully. Utils.ts:178 [2020-04-23T18:17:18.511Z] Debug: HttpConnection.stopConnection(Error: WebSocket closed with status code: 1011 ().) called while in state Connected.

Utils.ts:168 [2020-04-23T18:17:18.511Z] Error: Connection disconnected with error 'Error: WebSocket closed with status code: 1011 ().'.

Utils.ts:178 [2020-04-23T18:17:18.512Z] Debug: HubConnection.connectionClosed(Error: WebSocket closed with status code: 1011 ().) called while in state Connected.

Here's the function on the server side

        public async Task Host(string lobbyId)
        {
            //generate _lobbies here...
            await Clients.Others.SendAsync("ReceiveLobbies", 
                new { lobbies = new Lobby[] { _lobbies } })
        }

client side function "ReceiveLobbies" doesn't get called since the connection is closed. I have done a quick test and know that I can have multiple clients on localhost so why is this happening?


Solution

  • my Lobby object contains a list of Player objects that each have their own Lobby property, ergo an infinite recursion during serialization

    You can try to install the Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson NuGet package to switch to Newtonsoft.Json, then you can make it ignore circular references rather than throw an exception by set ReferenceLoopHandling setting, like below.

    services.AddSignalR().AddNewtonsoftJsonProtocol(opt=> {
        opt.PayloadSerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });