Flutter TCP Socket通信插件tcp_socket_flutter的使用
Flutter TCP Socket通信插件tcp_socket_flutter的使用
简介
这是一个允许你通过网络连接到Socket的Flutter插件。所有数据都使用UTF-8进行读取。
设置
配置
TCPSocketSetUp.setConfig(
const SocketConfig(
port: 8000,
numberSplit: 10000,
timeoutEachTimesSendData: Duration(milliseconds: 50),
),
);
初始化设备信息
await TCPSocketSetUp.init();
服务器端
final TCPSocketServer _server = TCPSocketServer();
final result = await _server.initServer(
onData: (ip, sourcePort, event) {
print('Server receive data from: $ip:$sourcePort');
print('Server receive data: $event');
},
onDone: (ip, sourcePort) {},
onError: (error, ip, sourcePort) {},
);
print(result);
服务器发送数据
await _server.sendData(
FormDataSending(
type: 'Server send info',
data: getRandomString(1000000),
),
);
客户端
final TCPSocketClient _client = TCPSocketClient();
final result = await _client.connectToServer(
'192.168.0.101',
onData: (event) {
print('Client receive data: $event');
},
onDone: () {},
onError: (error) {},
);
print('Connect to server $result');
客户端发送数据
await _client.sendData(
FormDataSending(
type: 'Client send info',
data: getRandomString(1000000),
),
);
许可证和贡献者
示例代码
以下是完整的示例代码:
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:tcp_socket_flutter/tcp_socket_flutter.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TCPSocketServer _server = TCPSocketServer();
final TCPSocketClient _client = TCPSocketClient();
final _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
final Random _rnd = Random();
String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MaterialButton(
color: Colors.blue,
onPressed: () async {
TCPSocketSetUp.setConfig(
const SocketConfig(
port: 8000,
numberSplit: 10000,
timeoutEachTimesSendData: Duration(milliseconds: 50),
),
);
print(TCPSocketSetUp.config.toJson());
},
child: const Text('设置端口为8000'),
),
const SizedBox(
height: 20,
),
MaterialButton(
color: Colors.blue,
onPressed: () async {
await TCPSocketSetUp.init();
print('获取设备信息完成');
},
child: const Text('获取IP信息'),
),
const SizedBox(
height: 20,
),
const Text('服务器 ------------'),
const SizedBox(
height: 20,
),
MaterialButton(
color: Colors.blue,
onPressed: () async {
final result = await _server.initServer(
onData: (ip, sourcePort, event) {
print('服务器接收数据来自: $ip:$sourcePort');
print('服务器接收数据: $event');
},
onDone: (ip, sourcePort) {},
onError: (error, ip, sourcePort) {},
);
print(result);
print('启动服务器成功');
},
child: const Text('启动服务器'),
),
MaterialButton(
color: Colors.blue,
onPressed: () async {
await _server.sendData(
FormDataSending(
type: '服务器发送信息',
data: getRandomString(1000000),
),
);
},
child: const Text('服务器发送数据'),
),
const SizedBox(
height: 20,
),
const Text('客户端 ------------'),
const SizedBox(
height: 20,
),
MaterialButton(
color: Colors.blue,
onPressed: () async {
final result = await _client.connectToServer(
'192.168.0.101',
onData: (event) {
print('客户端接收数据: $event');
},
onDone: () {},
onError: (error) {},
);
print('连接到服务器 $result');
},
child: const Text('连接到服务器'),
),
const SizedBox(
height: 20,
),
MaterialButton(
color: Colors.blue,
onPressed: () async {
await _client.sendData(
FormDataSending(
type: '客户端发送信息',
data: getRandomString(1000000),
),
);
},
child: const Text('客户端发送数据'),
),
],
),
),
);
}
}
更多关于Flutter TCP Socket通信插件tcp_socket_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter TCP Socket通信插件tcp_socket_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter应用中使用tcp_socket_flutter
插件来实现TCP Socket通信的示例代码。这个插件允许你建立TCP连接、发送和接收数据。
首先,确保你已经在pubspec.yaml
文件中添加了tcp_socket_flutter
依赖:
dependencies:
flutter:
sdk: flutter
tcp_socket_flutter: ^0.0.2 # 请检查最新版本号
然后,运行flutter pub get
来安装依赖。
以下是一个简单的示例,展示如何使用tcp_socket_flutter
插件来建立TCP连接、发送数据并接收响应:
import 'package:flutter/material.dart';
import 'package:tcp_socket_flutter/tcp_socket_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SocketCommunicationPage(),
);
}
}
class SocketCommunicationPage extends StatefulWidget {
@override
_SocketCommunicationPageState createState() => _SocketCommunicationPageState();
}
class _SocketCommunicationPageState extends State<SocketCommunicationPage> {
TCPSocket? _socket;
TextEditingController _messageController = TextEditingController();
String _response = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TCP Socket Communication'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextField(
controller: _messageController,
decoration: InputDecoration(labelText: 'Message'),
maxLines: 4,
),
SizedBox(height: 16),
ElevatedButton(
onPressed: _sendMessage,
child: Text('Send Message'),
),
SizedBox(height: 16),
Text('Response:\n$_response'),
],
),
),
);
}
Future<void> _connectToServer() async {
_socket = await TCPSocket.connect('192.168.1.100', 8080); // 替换为你的服务器地址和端口
if (_socket != null) {
_socket!.listen(
(Uint8List data) {
setState(() {
_response = String.fromCharCodes(data);
});
},
onError: (error) {
print('Error: $error');
},
onDone: () {
print('Connection closed');
},
cancelOnError: true,
);
}
}
Future<void> _sendMessage() async {
if (_socket == null || !_socket!.isOpen) {
await _connectToServer();
}
if (_socket != null && _socket!.isOpen) {
List<int> messageBytes = _messageController.text.codeUnits;
_socket!.write(messageBytes);
_messageController.clear();
} else {
print('Socket is not open');
}
}
@override
void dispose() {
_messageController.dispose();
_socket?.close();
super.dispose();
}
}
解释
-
依赖管理:在
pubspec.yaml
文件中添加tcp_socket_flutter
依赖。 -
UI构建:使用Flutter的Material Design组件来构建一个包含文本输入框、发送按钮和响应显示区的界面。
-
Socket连接:
_connectToServer
方法尝试连接到指定的服务器地址和端口。- 使用
TCPSocket.connect
方法建立连接,并监听数据接收事件。
-
发送消息:
_sendMessage
方法检查Socket是否已连接,如果未连接则调用_connectToServer
方法。- 使用
_socket!.write
方法将消息发送到服务器。
-
资源管理:在
dispose
方法中,释放文本控制器并关闭Socket连接,以防止内存泄漏。
注意
- 确保你有权限在设备上访问网络。
- 在实际部署中,处理异常和错误情况非常重要,这里仅展示了基本的实现。
- 你可能需要根据实际情况调整服务器地址和端口号。
这个示例代码提供了一个基本的框架,你可以在此基础上扩展以满足你的具体需求。