websocket flutter

https://stackoverflow.com/questions/51077233/how-can-i-use-socket-in-flutter-app

 

 

 

import 'dart:io';
import 'dart:async';

Socket socket;

void main() async{
  await Socket.connect("cn.whois-servers.net", 43).then((Socket sock) {
    socket = sock;
    socket.listen(dataHandler,
        onError: errorHandler,
        onDone: doneHandler,
        cancelOnError: false);
  }).catchError((AsyncError e) {
    print("Unable to connect: $e");
  });
  //Connect standard in to the socket
//  stdin.listen((data) => socket.write(new String.fromCharCodes(data).trim() + '\n'));
  socket.write('wuwu.cn\n');
}

void dataHandler(data){
  print('getting data');
  print(new String.fromCharCodes(data).trim());
}

void errorHandler(error, StackTrace trace){
  print(error);
}

void doneHandler(){
  socket.destroy();
}

  

 

 

import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
import 'dart:convert';


main()=>runApp(MaterialApp(home: MyApp(sock: SOCK(),),));

class MyApp extends StatelessWidget {
  MyApp({this.sock});
  final SOCK sock;
  TextEditingController _textController = TextEditingController();

  _send(){
    sock.send();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('test'),),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            StreamBuilder(
              stream: sock.sock,
              builder: (context, snapshot){
                if(snapshot.hasData){
                  return Text('has data');
                } else {
                  return Text('no data');
                }
              },
            ),
            TextField(controller: _textController,),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _send,
      ),
    );
  }
}

class SOCK {
  Socket sock;
  openSock () async{
    sock = await Socket.connect('cn.whois-servers.net', 43);
    sock.listen(onData);
    print('connecting');
  }

  send() async {
    print('sending from SOCK');
    await openSock();
    await sock.write('zizi.cn\n');
//    await sock.destroy();
  }

  onData(value){
    print('received');
//    var a = String.fromCharCodes(value);
    var b = utf8.decode(value);
    print(b);
  }
}

  

 

 

    原文作者:CrossPython
    原文地址: https://www.cnblogs.com/pythonClub/p/10693914.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞