Ad

How Can I Connect To TCP Socket (not Web Socket) In Flutter?

- 1 answer

import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'dart:io';
import 'package:flutter/material.dart';

void main() async {

  Socket sock = await Socket.connect('192.168.1.150', 2662);
  print('Connected to: ${sock.remoteAddress.address}:${sock.remotePort}');
  runApp(MyApp(sock));
  sock.listen(
       
        (Uint8List data) {
      final serverResponse = String.fromCharCodes(data);
      print('Server: $serverResponse');
    },
    
    onError: (error) {
      print(error);
      sock.destroy();
    },

    onDone: () {
      print('Server left.');
      sock.destroy();
    },
  );
}

class MyApp extends StatelessWidget {
  Socket socket;

  MyApp(Socket s) {
    this.socket = s;
    s.listen(

          (Uint8List data) {
        final serverResponse = String.fromCharCodes(data);
        print('Server: $serverResponse');
      },

      // handle errors
      onError: (error) {
        print(error);
        s.destroy();
      },

      onDone: () {
        print('Server left.');
        s.destroy();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final title = 'Example';
    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();
  }
}

When I run the code on the emulator, I get this error: " Debug service listening on ws://127.0.0.1:59871/2EzZsU03nwc=/ws Syncing files to device AOSP on IA Emulator..."

AND

"E/flutter (24126): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: SocketException: OS Error: Connection timed out, errno = 110, address = 192.168.1.131, port = 51170"

How can i solve this?

Thanks.

Ad

Answer

Here's pretty much the simplest Dart program to connect to a TCP socket on a server. It sends 'hello', waits 5 seconds for any reply, then closes the socket. You could use this with your own server, or a simple echo server like this one.

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

main() async {
  Socket socket = await Socket.connect('192.168.1.99', 1024);
  print('connected');

  // listen to the received data event stream
  socket.listen((List<int> event) {
    print(utf8.decode(event));
  });

  // send hello
  socket.add(utf8.encode('hello'));

  // wait 5 seconds
  await Future.delayed(Duration(seconds: 5));

  // .. and close the socket
  socket.close();
}
Ad
source: stackoverflow.com
Ad