我试图通过套接字控制dart脚本,在isolate中运行 我想出了一些(剧透警告)没有工作代码:
import "dart:io";
import "dart:convert";
import "dart:isolate";
reader(SendPort sendPort) async {
var serverSocket = await ServerSocket.bind("127.0.0.1", 83);
print('connected');
await for (var socket in serverSocket) {
socket.transform(UTF8.decoder).listen((msg) => sendPort.send(msg));
}
}
main() {
bool start = false;
bool stop = false;
listener (message)
{
print ("message from isolate: $message");
stop = start;
start = true;
}
ReceivePort receive = new ReceivePort();
receive.listen(listener);
Isolate.spawn(reader, receive.sendPort).then((Isolate) => print("Isolate started"));
print("Waiting to start");
while (!start) {}
print("Waiting to stop");
while (!stop) {}
print("Ended");
}
但是,似乎甚至没有启动隔离。只输出脚本是“等待开始”
答案 0 :(得分:2)
这对我有用:
import 'dart:async';
import "dart:io";
import "dart:convert";
import "dart:isolate";
reader(SendPort sendPort) async {
print('isolate started');
var serverSocket = await ServerSocket.bind("127.0.0.1", 8123);
sendPort.send('bound');
await for (var socket in serverSocket) {
socket.transform(UTF8.decoder).listen((msg) {
print('server received $msg');
sendPort.send(msg);
if (msg == 'close') {
socket.close();
serverSocket.close();
}
});
}
}
StreamSubscription subscription;
Isolate isolate;
ReceivePort receive;
main() async {
listener(message) async {
print("message from isolate: $message");
if (message == 'bound') {
final socket = await Socket.connect("127.0.0.1", 8123);
print('client connected');
socket.add('close'.codeUnits);
socket.destroy();
}
if (message == 'close') {
subscription.cancel();
// exits application
}
}
receive = new ReceivePort();
subscription = receive.listen(listener);
isolate = await Isolate.spawn(reader, receive.sendPort);
}