Could someone please show me an example of terminal input (question and response) in Dart (console) (latest r22223). The only example that I have seen doesn't appear to work or is incomplete.
Here's another option:
import "dart:async";
import "dart:io";
void main() {
stdout.write('> '); // stdout.write() rather than print() to avoid newline
new StringDecoder().bind(stdin).listen((str) { // Listen to a Stream<String>
print('"${str.trim()}"'); // Quote and parrot back the input
stdout.write('> '); // Prompt and keep listening
}, onDone: () => print('\nBye!')); // Stream is done, say bye
}
This appears to work fine on Linux and Windows. It quotes back to you whatever you enter at the prompt. You can exit by inputting EOF (control-D on Linux and other UNIX-like systems, control-Z followed by enter on Windows).
import "dart:async";
import "dart:io";
void main() {
print("Do you want to say something?");
Stream<String> input = stdin.transform(new StringDecoder());
StreamSubscription sub;
sub = input.listen((user_input) {
print("Really? \"${user_input.trim()}\"? That's all you have to say?");
sub.cancel();
});
}
Which example did you find, and how exactly was it wrong?
Related
I have this simple file:
class Console {
const Console();
void run() {
stdout
..writeln('Choose:\n')
..writeln(' 1) A')
..writeln(' 2) B\n')
final input = stdin.readLineSync() ?? '';
stdout.write('You have chosen $input');
}
}
How do I unit test this?
My best try is the following:
test('Making sure that invalid inputs return an error message', () async {
final process = await Process.start('dart', ['run', r'../bin/demo.dart']);
process.stdin.write('1');
process.stdout.transform(Utf8Decoder()).listen(print);
});
Since I have no idea on how to check for the stdout printed text, I am trying to at least display the strings
Choose:
1) A
2) B
using transform(Utf8Decoder()) but it's not working. Could you please point me towards the right direction?
Note: the main() function is located in lib/demo.dart so that's why I'm passing ../bin/demo.dart
Is it possible to run an external command in Dart? I need to run the external command plutil, but everything I google gives me results to run Dart code from the command line, so I have not been able to find a solution. Thanks!
Example of Run external command in dart:
import 'dart:io';
void main(List<String> args) async {
var executable = 'ls';
if (Platform.isWindows) {
executable = 'dir';
}
final arguments = <String>[];
print('List Files and Directories');
print('============');
final process = await Process.start(executable, arguments, runInShell: true);
await stdout.addStream(process.stdout);
await stderr.addStream(process.stderr);
final exitCode = await process.exitCode;
print('============');
print('Exit code: $exitCode');
}
This is the backbone of a simple program that uses a StreamController to listen on some input stream and outputs some other data on its own stream as a reaction:
import 'dart:async';
main() async {
var c = StreamController(
onListen: (){},
onPause: (){},
onResume: (){},
onCancel: (){});
print("start");
await for (var data in c.stream) {
print("loop");
}
print("after loop");
}
Output:
$ dart cont.dart
start
$ dart
Why does this code exit immediately at the await for line without executing neither print("loop") nor print("after loop") ?
Note: in the original program, onListen() will receive the input stream and subscribe to it. The loop actually works until calling subscription.cancel() on the input stream, when it also suddenly exits, without any chance to clean up.
I was surprised by this, but then again all of async/await code is converted to .then()s and it seems everything can't be perfectly translated.
It seems this is part of the answer: You need to close the stream in another task to get out of the await for. Here is a previous related question. Since we don't close it, lines after await for do not execute. Here's an example that avoids this:
import 'dart:async';
main() async {
var c = StreamController(
onListen: () {},
onPause: () {},
onResume: () {},
onCancel: () {});
print("start");
await Future.wait(<Future>[producer(c), consumer(c)]);
print("after loop");
}
Future producer(StreamController c) async {
// this makes it print "loop" as well
// c.add("val!");
await c.close();
}
Future consumer(StreamController c) async {
await for (var data in c.stream) {
print("loop");
}
}
which prints:
start
after loop
So, moral of the story is,
Never leave a StreamController unattended or weird things will happen.
Some async functions that you wait on will break your code, even bypassing your try/finally block!
I thought I knew async/await inside out, but this second point scares me now.
Is there any way to establish a telnet connection in dart?
Basically what I want to achive it's to create a teamspeak 3 bot using Dart.
I tought about using socket with I have no idea about how to go on.
EDIT: I managed to estabilish a socket connection to the ts3 but I cannot make dart to keep the connection open:
EDIT: Managed to keep the connection open
EDIT: Now the commands are sent but the spaces are not recognized.
EDIT: \u0020 made the space work but the param(login) it's not read
EDIT: Finally all it's working, \n was required at the string end.
import 'dart:io';
import 'dart:async';
const String user = "serveradmin";
const String pass = "------";
Socket socket;
void main() async {
await Socket.connect("localhost", 10011)
.then((Socket sock) {
socket = sock;
socket.listen(dataHandler,
onError: errorHandler,
onDone: doneHandler,
cancelOnError: false);
})
.catchError((AsyncError e) {
print("Unable to connect: $e");
exit(1);
});
socket.write('help login\n');
print("End main");
}
void dataHandler(data){
print("Data Handler!");
print(" ${new String.fromCharCodes(data).trim()}");
socket.write(new String.fromCharCodes(data).trim() + 'help login');
}
void errorHandler(error, StackTrace trace){
print(error);
}
void doneHandler(){
print("Done Handler!");
socket.destroy();
exit(0);
}
Also seems like to login command it's not sent.
import 'dart:io';
import 'dart:async';
void main() {
HttpClient client = new HttpClient();
client.getUrl(Uri.parse('http://api.dartlang.org/docs/releases/latest/dart_io/HttpClientResponse.html'))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
response.listen(print, onError: (e) {
print('error: $e');
});
});
}
The code above doesn't work, using similar method to listen like pipe and fold also throws an exception => Breaking on exception: The null object does not have a method 'cancel'.
Update
Here's the code example for when connect to local machine.
import 'dart:io';
import 'dart:async';
void main() {
HttpServer.bind('127.0.0.1', 8080)
.then((HttpServer server) {
server.listen((HttpRequest request) {
File f = new File('upload.html');
f.openRead().pipe(request.response);
});
HttpClient client = new HttpClient();
client.getUrl(Uri.parse('http://127.0.0.1:8080'))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
response.listen(print, onError: (e) {
print('error: $e');
});
});
});
}
It prints out the bytes first and then throw an exception Breaking on exception: The null object does not have a method 'cancel'.
Dart Editor version 0.7.2_r27268. Dart SDK version 0.7.2.1_r27268. On Windows 64bit machine.
Your example works on my machine.
Please specify your Dart version and other system properties that could help debug the problem.
The code presented looks fine, and I have not been able to reproduce the error on either 0.7.2.1 nor bleeding edge. Do you know whether you network has any kind of proxy setup which could cause a direct HTTP connection to fail? You could try connecting to a server on your local machine instead. If it still fails I suggest opening a bug on https://code.google.com/p/dart/issues/list with detailed information.