forked from dart-archive/dart-tutorials-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumber_thinker.dart
More file actions
53 lines (46 loc) · 1.63 KB
/
Copy pathnumber_thinker.dart
File metadata and controls
53 lines (46 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Use the client program, number_guesser.dart to automatically make guesses.
// Or, you can manually guess the number using the URL localhost:4045/?q=#,
// where # is your guess.
// Or, you can use the make_a_guess.html UI.
import 'dart:io';
import 'dart:math' show Random;
int myNumber = new Random().nextInt(10);
main() async {
print("I'm thinking of a number: $myNumber");
HttpServer requestServer =
await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 4041);
await for (var request in requestServer) {
handleRequest(request);
}
}
void handleRequest(HttpRequest request) {
try {
if (request.method == 'GET') {
handleGet(request);
} else {
request.response..statusCode = HttpStatus.METHOD_NOT_ALLOWED
..write('Unsupported request: ${request.method}.')
..close();
}
} catch (e) {
print('Exception in handleRequest: $e');
}
print('Request handled.');
}
void handleGet(HttpRequest request) {
var guess = request.uri.queryParameters['q'];
request.response.statusCode = HttpStatus.OK;
if (guess == myNumber.toString()) {
request.response..writeln('true')
..writeln("I'm thinking of another number.")
..close();
myNumber = new Random().nextInt(10);
print("I'm thinking of another number: $myNumber");
} else {
request.response..writeln('false')
..close();
}
}