gpt4 book ai didi

sockets - 在 dart 中将 SocketServer 作为 Isolate 运行

转载 作者:行者123 更新时间:2023-12-03 02:53:36 25 4
gpt4 key购买 nike

我正在尝试通过套接字控制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");
}

但是isolate似乎还没有启动。脚本的唯一输出是“等待开始”

最佳答案

这对我有用:

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

关于sockets - 在 dart 中将 SocketServer 作为 Isolate 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44981115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com