Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect Flutter app to tcp socket server?

I had great difficulties to connect Flutter app to my network tcp socket on server. I know I have to use some sort intermediate option so translate data between tcp socket to flutter and Flutter to tcp socket.

Any idea, info how do achieve this. And question is How to connect Flutter app to tcp socket server?

like image 971
Nick Avatar asked Feb 01 '19 14:02

Nick


1 Answers

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();
}
like image 187
Richard Heap Avatar answered Oct 06 '22 07:10

Richard Heap