How can i connect to TCP socket (not web socket) in flutter?
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();
}
Metehan Gezer
Software and programming is also someone who works to take himself to the highest levels. I am always open to innovations and I like to produce my own ideas... Metehan Gezer
Updated on January 01, 2023Comments
-
Metehan Gezer over 1 year
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.
-
Metehan Gezer over 2 yearshi, i did what you said but i am getting the same error again. E/flutter (25374): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: SocketException: OS Error: Connection timed out, errno = 110, address = 192.168.1.150, port = 58384
-
G H Prakash over 2 yearsCan you try to clean and run again?
-
Metehan Gezer over 2 yearsI opened the terminal. I did flutter -clear and then flutter-run it built it but unfortunately it gave the same error.
-
Metehan Gezer over 2 yearsHi G H Prakash, How to send a message when a button is pressed with Flutter TCP socket? thanks...
-
West about 2 yearsI have a receiver in python with bind
socket.bind("tcp://127.0.0.1:5556")
I connected with flutter usingsocket = await Socket.connect('127.0.0.1', 5556);
but when I send a message withsocket.add(utf8.encode('hello'));
nothing is received in other program