How to connect Flutter app to tcp socket server?

2020-07-19 03:52发布

问题:

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?

回答1:

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