如何在Flutter应用中使用套接字?

时间:2018-06-28 07:34:28

标签: dart flutter

我创建了Flutter应用。我需要将我的应用程序连接到本地网络套接字服务。如下所示,我可以使用telnet Connect,发送数据和从服务器接收数据。我使用Flutter web_socket插件和示例。我可以连接到服务器并发送数据,但是我无法捕获(或获取数据,但没有显示任何内容。)数据。在Flutter的Google网上论坛中,有人建议我使用流而不是StreamBuilder。

To send data I use;         Q101:_:49785:_:ABCDE
And receive data I get;     1:_:2:_:119351:_:NİYAZİ TOROS 

当我使用此示例(https://flutter.io/cookbook/networking/web-sockets/)时,套接字服务出现错误,如下所示:

Q: 28.06.2018 08:53:57->GET / HTTP/1.1
A: 28.06.2018 08:53:57 ->:1:_:1:_:FAIL1

示例:

Last login: Tue Jun 26 15:01:44 on ttys000
Niyazis-MBP:~ niyazitoros$ telnet
telnet> telnet 192.168.1.22 1024
Trying 192.168.1.22...
Connected to 192.168.1.22.
Escape character is '^]'.
Q101:_:49785:_:*************
1:_:2:_:119351:_:NİYAZİ TOROS

基于@Richard Heap的建议:

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

void connect(InternetAddress clientAddress, int port) {
  Future.wait([RawDatagramSocket.bind(InternetAddress.anyIPv4, 0)]).then(
      (values) {
    RawDatagramSocket _socket = values[0];
    _socket.listen((RawSocketEvent e) {
      print(e);
      switch (e) {
        case RawSocketEvent.read:
          Datagram dg = _socket.receive();
          if (dg != null) {
            dg.data.forEach((x) => print(x));
          }
          _socket.writeEventsEnabled = true;
          break;
        case RawSocketEvent.write:
          _socket.send(
              new Utf8Codec().encode('Hello from client'), clientAddress, port);
          break;
        case RawSocketEvent.closed:
          print('Client disconnected.');
      }
    });
  });
}

main(List<String> arguments) {
  print("Connecting to server..");
  var address = new InternetAddress('192.168.1.22');
  int port = 1024;
  connect(address, port);
}

我明白了:

/Users/niyazitoros/flutter/bin/cache/dart-sdk/bin/dart --enable-asserts --enable-vm-service:59683 /Users/niyazitoros/IdeaProjects/github/untitled/bin/main.dart
Observatory listening on http://127.0.0.1:59683/

Connecting to server..
RawSocketEvent.write

3 个答案:

答案 0 :(得分:3)

如attdona所述,

  

您的服务器不会使用websocket协议,但会公开一个普通的TCP套接字。

因此,您需要一个TCP套接字,并且有一个关于SocketsServerSockets的出色教程,您可以找到here

这是一个片段:

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();
}

答案 1 :(得分:2)

您的服务器不会使用websocket协议,但会公开一个普通的TCP套接字。

这是一个与普通tcp套接字配合使用的示例,改编自https://flutter.io/cookbook/networking/web-sockets flutter食谱示例:

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();
  }
}

答案 2 :(得分:0)

$('#table').dataTable({
   //your table settings here..
   initComplete : function() {
      if ($(this).find('tbody tr').length<=1) {
         $('#table').parents('div.dataTables_wrapper').first().hide();
      }
   } 
});