running SocketServer as Isolate in dart

Issue

I am trying to control dart script via socket, running within isolate
I came up with some (spoiler warning) not working code:

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

But isolate does not even seem to be launched. Only output of script is “Waiting to start”

Solution

This worked for me:

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

Answered By – Günter Zöchbauer

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.