Skip to content

Instantly share code, notes, and snippets.

@DiegoCarvalho75
Forked from pyzenberg/main.dart
Created September 4, 2020 21:08
Show Gist options
  • Save DiegoCarvalho75/9ce57ef15d105eae981309b0b57c2549 to your computer and use it in GitHub Desktop.
Save DiegoCarvalho75/9ce57ef15d105eae981309b0b57c2549 to your computer and use it in GitHub Desktop.
Flutter WebSocket autoconnection
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