signalr_core
signalr_core copied to clipboard
Duplicate connections on hot restart, any way to close all connections without handles to them?
Hi,
I'm trying this lib but I get multiple connections when using hot restart (both on mobile and web). This isn't a big issue in mobile since the end users in production cannot "hot restart" the app with flutter for web, an end user can refresh the browser at any given time and thus creating multiple connections.
This is easy to reproduce, just connect in initState() or something similar, like the example:
final connection = HubConnectionBuilder().withUrl('http://localhost:5000/chatHub',
HttpConnectionOptions(
logging: (level, message) => print(message),
)).build();
await connection.start();
connection.on('ReceiveMessage', (message) {
print(message.toString());
});
await connection.invoke('SendMessage', args: ['Bob', 'Says hi!']);
With a server that can accept "SendMessage" and that replies with "ReceiveMessage" we will get an output in the debug console: Bob Says hi!
.
This is great, just like we want. We will close the socket on dispose() but with hot restart we are not calling dispose() (at least not in flutter for web).
But after hot restart, initState will initialize a connection but the old one is still there! So we get two lines in debug console:
Bob Says hi!
Bob Says hi!
If we hot restart again, we have three connections:
Bob Says hi!
Bob Says hi!
Bob Says hi!
This is can be solved by closing all connections before creating a new one, either automatically or expose a "closeAllConnections()" call. I've seen that adhara_socket_io library has this in their 1.0.0 release (https://pub.dev/packages/adhara_socket_io/changelog#100---3rd-apr-2020)
I also saw this related answer to a similar post on an issue for adhara_socket_io: https://github.com/infitio/flutter_socket_io/issues/6#issuecomment-570936883
Any way that I can achieve this with current version of signalr_core lib?
hi @mikeesouth, did you solve the issue.. I'm facing a similar issue you have described the problem with adhara_socket_io is that it is not null safety and hence I can't implement it in my application.
@santosh2221994 I haven't investigated it further but I believe that the debug console is showing logs from previous instances of the application but the application itself works correctly. In my example in the original post I stated that I got three "Bob Says hi!" after two hot restarts. That's still the case but if I show the log in my application interface, I only get one "Bob Says hi!" even after two hot restarts.
I'm not sure if this is an issue or not but if you react to websocket requests and show a chat message or whatever, then your user interface will only show one message even after two hot restarts (not three). It feels a bit odd that the debug console is still showing messages from the old (discarded?) instances of the application though.
It is can be handled from background and drop old connection.