-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-prime-time.rkt
More file actions
43 lines (35 loc) · 1.14 KB
/
02-prime-time.rkt
File metadata and controls
43 lines (35 loc) · 1.14 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
#lang racket
(require json)
(require (only-in math/number-theory
prime?))
(define (serve port-no)
(define listener (tcp-listen port-no 5 #f))
(define (loop)
(accept-and-handle listener)
(loop))
(define t (thread loop))
(λ ()
(kill-thread t)
(tcp-close listener)))
(define (accept-and-handle listener)
(define-values (in out) (tcp-accept listener))
(thread
(λ ()
(handle in out)
(close-input-port in)
(close-output-port out))))
(define (is-valid expr)
(and (equal? "isPrime" (hash-ref expr 'method null))
(let ([n (hash-ref expr 'number null)])
(or (integer? n) (rational? n)))))
(define (handle in out)
(define line (read-line in))
(with-handlers ([exn:fail? (λ (exn)
(newline out)
(flush-output out))])
(define msg (with-input-from-string line read-json))
(when (not (is-valid msg)) (error 'invalid))
(write-json (hash 'method "isPrime" 'prime (let ([n (hash-ref msg 'number)]) (and (integer? n) (> n 0) (prime? n)))) out)
(newline out)
(flush-output out)
(handle in out)))