Using Socket in Flutter apps?

前端 未结 3 1550
有刺的猬
有刺的猬 2020-12-16 22:23

I create a Flutter App. I need to connect my app to local network socket services. As shown below, I can use telnet Connect, Send data and Receive data from the server. I us

相关标签:
3条回答
  • 2020-12-16 22:48

    Your server does not speak the websocket protocol but it exposes a plain tcp socket.

    This is an example that works with a plain tcp socket, adapted from https://flutter.io/cookbook/networking/web-sockets flutter cookbook example:

    import 'package:flutter/foundation.dart';
    import 'dart:io';
    import 'package:flutter/material.dart';
    
    void main() async {
      // modify with your true address/port
      Socket sock = await Socket.connect('192.168.1.129', 10000);
      runApp(MyApp(sock));
    }
    
    class MyApp extends StatelessWidget {
      Socket socket;
    
      MyApp(Socket s) {
        this.socket = s;
      }
    
      @override
      Widget build(BuildContext context) {
        final title = 'TcpSocket Demo';
        return MaterialApp(
          title: title,
          home: MyHomePage(
            title: title,
            channel: socket,
          ),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      final String title;
      final Socket channel;
    
      MyHomePage({Key key, @required this.title, @required this.channel})
          : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      TextEditingController _controller = TextEditingController();
    
      @override
      Widget build(BuildContext context) {
    
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Form(
                  child: TextFormField(
                    controller: _controller,
                    decoration: InputDecoration(labelText: 'Send a message'),
                  ),
                ),
                StreamBuilder(
                  stream: widget.channel,
                  builder: (context, snapshot) {
                    return Padding(
                      padding: const EdgeInsets.symmetric(vertical: 24.0),
                      child: Text(snapshot.hasData
                          ? '${String.fromCharCodes(snapshot.data)}'
                          : ''),
                    );
                  },
                )
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _sendMessage,
            tooltip: 'Send message',
            child: Icon(Icons.send),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    
      void _sendMessage() {
        if (_controller.text.isNotEmpty) {
          widget.channel.write(_controller.text);
        }
      }
    
      @override
      void dispose() {
        widget.channel.close();
        super.dispose();
      }
    }
    
    0 讨论(0)
  • 2020-12-16 22:53

    As attdona mentioned,

    Your server does not speak the websocket protocol but it exposes a plain tcp socket.

    So you need a TCP socket and there is a great tutorial on Sockets and ServerSockets which you can find here.

    Here's a snippet:

    import 'dart:io';
    import 'dart:async';
    
    Socket socket;
    
    void main() {
       Socket.connect("localhost", 4567).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'));
    }
    
    void dataHandler(data){
       print(new String.fromCharCodes(data).trim());
    }
    
    void errorHandler(error, StackTrace trace){
       print(error);
    }
    
    void doneHandler(){
       socket.destroy();
    }
    
    0 讨论(0)
  • 2020-12-16 23:06
    Socket.connect(localhost, port).then((socket){
                print('socket $socket');
                socket.listen((Data){
                  print(new Code().decode(Data));
                });
              });
    
    0 讨论(0)
提交回复
热议问题