Skip to content

Instantly share code, notes, and snippets.

@pyzenberg
Created September 4, 2019 13:38
Show Gist options
  • Save pyzenberg/4037e11627a8cac1c442183cc7cf172a to your computer and use it in GitHub Desktop.
Save pyzenberg/4037e11627a8cac1c442183cc7cf172a 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;
}
}
@vimalmistry
Copy link

@pyzenberg This works nice. But How to send message to the server. I tried using ws.addStream('from client') but It not accepting text.

@fzyzcjy
Copy link

fzyzcjy commented Apr 17, 2020

@vimalmistry maybe ws.add('mytext')?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment