2

我试图通过套接字控制飞镖脚本,在隔离内运行我想出了一些(剧透警告)不起作用的代码:

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");
}

但是隔离似乎甚至没有启动。脚本的唯一输出是“等待开始”

4

1 回答 1

3

这对我有用:

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);
}
于 2017-07-08T14:51:47.717 回答