-
-
Save DiegoCarvalho75/9ce57ef15d105eae981309b0b57c2549 to your computer and use it in GitHub Desktop.
Flutter WebSocket autoconnection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
class HomePage extends StatefulWidget { | |
@override | |
_HomePageState createState() => _HomePageState(); | |
} | |
class _HomePageState extends State<HomePage> { | |
WebSocket ws; | |
final String url = 'wss://YOUR-WEBSOCKET-URL'; | |
int wsDelaySeconds = 10; | |
bool stateConnectionLost; | |
@override | |
void initState() async { | |
super.initState(); | |
await _wsListen(); | |
} | |
_wsListen() async { | |
ws = await WebSocket.connect(url); | |
ws.listen( | |
(data){ | |
print("@@ data: $data"); | |
}, | |
cancelOnError: true, | |
onDone: () { | |
print("@@ connection done"); | |
setState(() { stateConnectionLost = true; }); | |
ws = null; | |
print('@@ waiting for $wsDelaySeconds seconds'); | |
Timer.periodic(Duration(seconds:wsDelaySeconds), (Timer timer) async { | |
try { | |
print("@@ retry"); | |
await _wsListen(); | |
} catch (e) { | |
print("@@ error: $e"); | |
} | |
if (ws != null) timer.cancel(); | |
}); | |
} | |
); | |
} | |
@override | |
Widget build(BuildContext context) { | |
// TODO: implement build | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment