我很难将Flutter应用程序连接到我的服务器上的网络TCP套接字。 我知道我必须使用某种中间选项,以在TCP套接字与Flutter之间进行数据传输。
有任何想法、信息可以帮助我实现这个过程吗?问题是如何将Flutter应用程序连接到TCP套接字服务器?
这是一个连接到服务器上的TCP套接字的最简单Dart程序。它发送“hello”,等待5秒钟任何回复,然后关闭套接字。您可以将其与自己的服务器或简单的回声服务器(如此处)一起使用。
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();
}
Socket s = await Socket.connect(host, port);
如果需要SSL/TLS,请使用SecureSocket
。如果需要HTTPS,请使用HttpClient
或package:http
。 - Richard Heap