Dart编写一个TCP客户端Flutter界面程序
时间: 2023-08-08 22:13:21 浏览: 189
以下是一个使用Dart编写的TCP客户端Flutter界面程序的示例:
```dart
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
class TcpClient extends StatefulWidget {
@override
_TcpClientState createState() => _TcpClientState();
}
class _TcpClientState extends State<TcpClient> {
final TextEditingController _hostController = TextEditingController();
final TextEditingController _portController = TextEditingController();
final TextEditingController _messageController = TextEditingController();
Socket? _socket;
void _connect() async {
try {
final host = _hostController.text;
final port = int.parse(_portController.text);
_socket = await Socket.connect(host, port);
setState(() {});
} catch (e) {
print('Error: $e');
}
}
void _sendMessage() {
final message = _messageController.text;
_socket?.write(message);
_messageController.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TCP Client'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _hostController,
decoration: InputDecoration(
labelText: 'Host',
),
),
SizedBox(height: 8),
TextField(
controller: _portController,
decoration: InputDecoration(
labelText: 'Port',
),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: _connect,
child: Text('Connect'),
),
SizedBox(height: 16),
if (_socket != null)
Expanded(
child: StreamBuilder(
stream: _socket!.transform(utf8.decoder),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SingleChildScrollView(
child: Text(snapshot.data.toString()),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
),
SizedBox(height: 16),
if (_socket != null)
TextField(
controller: _messageController,
decoration: InputDecoration(
labelText: 'Message',
),
),
SizedBox(height: 8),
if (_socket != null)
ElevatedButton(
onPressed: _sendMessage,
child: Text('Send'),
),
],
),
),
);
}
}
```
在此示例中,我们使用 `Socket.connect` 方法连接到指定的主机和端口。我们还使用 `StreamBuilder` 将接收到的数据流转换为可读文本,并将其显示在屏幕上。最后,我们还实现了一个发送消息的方法,该方法将文本框中的消息写入到套接字中。
阅读全文