Reputation: 3168
I use this library (socket.io) in my flutter app for instant messaging using web sockets.
There are 2 screens - Home
and Chat
. After a form input from Home
screen, the app navigates to Chat
screen, inside initState()
method of which, I have written the code to establish the socket connection:
IO.Socket socket;
void initState() {
socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'query': {
'timeStamp': new DateTime.now().millisecondsSinceEpoch
}
});
socket.on('connect', (_) {
print("debug: connected");
});
});
The connection works the first time I navigate from Home
to Chat
. But, If I navigate back to the Home
page and then come back to Chat
, the connection doesn't work. What could be the reason?
This is the code for navigating back to the Home
page:
onPressed: () {
socket.destroy();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(),
),
(x) => false);
},
No action is done on socket inside the dispose()
method of the widget.
Upvotes: 0
Views: 1373
Reputation: 3168
This is because it tries to reuse the same socket for connections to the same host. The solution is to use 'force new connection': true
on connection.
socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'force new connection': true,
'query': {
'timeStamp': new DateTime.now().millisecondsSinceEpoch
}
});
Upvotes: 4