【发布时间】:2019-12-19 21:05:51
【问题描述】:
我正在尝试在 Dart 中实现一个协议。
基本上,我需要创建一些类似于ask_for_help的方法(见下文)。
这是我目前的代码:
const int DEFAULT_TIMEOUT = 3;
class MySocket {
/// The host server
String _host;
/// The TCP port number
int _port;
/// The status of the socket (connected or not)
bool _isConnected = false;
/// The connection timeout
Duration _timeout;
/// The connected socket (if any, see [_isConnected])
Socket _socket;
/// Establish a connection with the [host] on given [port]
///
/// Throws a [SocketException] if connection cannot be established.
Future<void> connect(String host, int port,
{int timeout = DEFAULT_TIMEOUT}) async {
_host = host;
_port = port;
_timeout = Duration(seconds: timeout);
_socket = await Socket.connect(host, port, timeout: _timeout);
_isConnected = true;
_socket.listen(default_handler);
}
/// Send [cmd] command to the connected server
void send_request(String cmd) {
_socket.writeln(cmd);
}
/// Close the connection with the server
void close() {
_isConnected = false;
_socket.close();
}
void ask_for_help() {
var cmd = 'HELP';
send_request(cmd);
// Start listening to the socket
// Wait for a response
// Stop listening to the socket
// Consume response from the Stream
// Do something with that response (e.g print it on stdout)
}
}
void default_handler(Uint8List message) {
print('----- RESPONSE STARTS HERE -----');
print(String.fromCharCodes(message).trim());
print('----- RESPONSE ENDS HERE -----');
}
然后我有几个问题:
- 如何让
ask_for_help监听套接字直到收到响应? - 如何确保每个方法都能读取正确的响应而不是另一个? (如果在服务器应答之前发送了多个请求)
关于第二个问题的备注:使用上面的代码,当我发送多个请求时,它们之间没有延迟,所有响应都聚集在一起。这意味着我不知道应该用什么函数来处理它。
欢迎提出任何建议。
【问题讨论】:
标签: dart