Created
September 4, 2019 13:38
-
-
Save pyzenberg/4037e11627a8cac1c442183cc7cf172a to your computer and use it in GitHub Desktop.
Flutter WebSocket autoconnection
This file contains hidden or 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
@pyzenberg This works nice. But How to send message to the server. I tried using
ws.addStream('from client')
but It not accepting text.