nailgilaziev

dart ws io with done

Jun 7th, 2018
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 5.16 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:io';
  3.  
  4. import 'package:flutter/foundation.dart';
  5. import 'package:flutter/material.dart';
  6.  
  7.  
  8. void main() => runApp(new MyApp());
  9.  
  10. class MyApp extends StatelessWidget {
  11.   @override
  12.   Widget build(BuildContext context) {
  13.     final title = 'WebSocket Demo';
  14.     return new MaterialApp(
  15.       title: title,
  16.       home: new MyHomePage(
  17.         title: title,
  18. //        wsurl: 'ws://echo.websocket.org',
  19. //        wsurl: 'wss://afternoon-sierra-23732.herokuapp.com/events',
  20.         wsurl: 'ws://192.168.2.2:8080/events',
  21. //        wsurl: 'ws://10.18.8.73:8080/events',
  22.       ),
  23.     );
  24.   }
  25. }
  26.  
  27. class MyHomePage extends StatefulWidget {
  28.   final String title;
  29.   final String wsurl;
  30.  
  31.   MyHomePage({Key key, @required this.title, @required this.wsurl})
  32.       : super(key: key);
  33.  
  34.   @override
  35.   _MyHomePageState createState() => new _MyHomePageState();
  36. }
  37.  
  38. class _MyHomePageState extends State<MyHomePage> {
  39.   TextEditingController _controller = new TextEditingController();
  40.   Future<WebSocket> wsFuture;
  41.   WebSocket ws;
  42.   Exception ex;
  43.   String transferredData;
  44.  
  45.  
  46.  
  47.   initws() {
  48.     transferredData = null;
  49.     ex = null;
  50.     ws = null;
  51.     wsFuture = WebSocket
  52.         .connect(widget.wsurl)
  53.         .timeout(new Duration(seconds: 15))
  54.         .then((v) {
  55.       setState(() {
  56.         ws = v;
  57.         ws.pingInterval = new Duration(seconds: 240);
  58.         ws.handleError((e, s) {
  59.           timeprint("ERROR HANDLED $e");
  60.         });
  61.         ws.done.then((v) {
  62.           setState(() {
  63.             ex = new Exception("Connection is done with v=$v");
  64.             timeprint("DONE");
  65.           });
  66.         });
  67.         ws.listen((d) {
  68.           setState(() {
  69.             transferredData = d;
  70.             timeprint("DATA RECEIVED");
  71.           });
  72.         }, onError: (e, stack) {
  73.           setState(() {
  74.             ex = e;
  75.             timeprint("ERROR ON LISTEN");
  76.           });
  77.         }, onDone: () {
  78.           ex = new Exception("Connection is done with v=$v");
  79.           timeprint("DONE ON LISTEN");
  80.         });
  81.       });
  82.     }, onError: (e, stack) {
  83.       timeprint("onerror $e");
  84.       setState(() {
  85.         ex = e;
  86.       });
  87.     });
  88.     timeprint("inited");
  89.   }
  90.  
  91.   timeprint(msg){
  92.     print(new DateTime.now().toString() + "    " +  msg);
  93.   }
  94.  
  95.   Widget getUI() {
  96.     if (ex != null) {
  97.       return new Text("err " + ex.toString(),
  98.           style: new TextStyle(color: Colors.red));
  99.     }
  100.     if (ws == null) {
  101.       return new CircularProgressIndicator();
  102.     }
  103.     if (transferredData != null) {
  104.       return new Text(transferredData);
  105.     }
  106.   }
  107.  
  108.   @override
  109.   void initState() {
  110.     initws();
  111.     super.initState();
  112.   }
  113.  
  114.   @override
  115.   Widget build(BuildContext context) {
  116.     return new Scaffold(
  117.       appBar: new AppBar(
  118.         title: new Text(widget.title),
  119.       ),
  120.       body: new Padding(
  121.         padding: const EdgeInsets.all(20.0),
  122.         child: new Column(
  123.           crossAxisAlignment: CrossAxisAlignment.start,
  124.           children: <Widget>[
  125.             new Padding(
  126.                 padding: const EdgeInsets.symmetric(vertical: 24.0),
  127.                 child: getUI()),
  128.             new Form(
  129.               child: new TextFormField(
  130.                 controller: _controller,
  131.                 decoration: new InputDecoration(labelText: 'Send a message'),
  132.               ),
  133.             ),
  134.             new Padding(
  135.               padding: const EdgeInsets.only(top: 8.0),
  136.               child: new Row(
  137.                 children: <Widget>[
  138.                   new RaisedButton(
  139.                     onPressed: () {
  140.                       setState(() {
  141.                         initws();
  142.                       });
  143.                     },
  144.                     child: new Text("Reconnect"),
  145.                   ),
  146.                   new SizedBox(
  147.                     width: 8.0,
  148.                   ),
  149.                   new RaisedButton(
  150.                     onPressed: () {
  151.                       if (ws == null) {
  152.                         print("ws is not inited yet");
  153.                         return;
  154.                       }
  155.                       print("ready state ${ws.readyState}");
  156.                       print("close code ${ws.closeCode}");
  157.                       print("close reason ${ws.closeReason}");
  158.                       print("extensions ${ws.extensions}");
  159.                       print("protocol ${ws.protocol}");
  160.                     },
  161.                     child: new Text("check state"),
  162.                   ),
  163.                 ],
  164.               ),
  165.             )
  166.           ],
  167.         ),
  168.       ),
  169.       floatingActionButton: new FloatingActionButton(
  170.         onPressed: _sendMessage,
  171.         tooltip: 'Send message',
  172.         child: new Icon(Icons.send),
  173.       ), // This trailing comma makes auto-formatting nicer for build methods.
  174.     );
  175.   }
  176.  
  177.   void _sendMessage() {
  178.     if (ws != null) {
  179.       if (_controller.text.isNotEmpty) {
  180.         ws.add(_controller.text);
  181.         _controller.text = "";
  182.         timeprint("Sended");
  183.       }
  184.     } else {
  185.       print("WS IS NOT FILLED!!!!");
  186.     }
  187.   }
  188.  
  189.   @override
  190.   void dispose() {
  191. //    wsChannel.sink.close();
  192.     super.dispose();
  193.   }
  194. }
Advertisement
Add Comment
Please, Sign In to add comment