flutter下好用的websocket插件

先上GitHub地址:https://github.com/ZClee128/better_socket
flutter包地址:https://pub.flutter-io.cn/packages/better_socket

这个和dart的websocket不一样,因为这个是调用原生稳定的websocket库,同时支持iOS和安卓,使用起来比dart的websocket库好用

使用方式

import 'package:flutter/material.dart';
import 'package:better_socket/better_socket.dart';
import 'dart:convert';

class WebSocketRoute extends StatefulWidget {
  @override
  _WebSocketRouteState createState() => new _WebSocketRouteState();
}

class _WebSocketRouteState extends State {
  TextEditingController _controller = new TextEditingController();
  // IOWebSocketChannel channel;
  String _text = "";

  @override
  void initState() {
    //创建websocket连接
    var headers = {"origin": "ws://echo.websocket.org"};
    BetterSocket.connentSocket("ws://echo.websocket.org", httpHeaders: headers);
    BetterSocket.addListener(onOpen: (httpStatus, httpStatusMessage) {
      print(
          "onOpen---httpStatus:$httpStatus  httpStatusMessage:$httpStatusMessage");
    }, onMessage: (message) {
      setState(() {
        _text = message;
      });
      print("onMessage---message:$message");
    }, onClose: (code, reason, remote) {
      print("onClose---code:$code  reason:$reason  remote:$remote");
    }, onError: (message) {
      print("onError---message:$message");
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("WebSocket(内容回显)"),
      ),
      body: new Padding(
        padding: const EdgeInsets.all(20.0),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            new Form(
              child: new TextFormField(
                controller: _controller,
                decoration: new InputDecoration(labelText: 'Send a message'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 24.0),
              child: new Text(_text),
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: new Icon(Icons.send),
      ),
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      
      BetterSocket.sendMsg(_controller.text);
      
      BetterSocket.sendByteMsg(Utf8Encoder().convert('hello'));
    }
  }

  @override
  void dispose() {
    BetterSocket.close();
    super.dispose();
  }
}

你可能感兴趣的:(flutter下好用的websocket插件)