Changed the communication protocol: the first 4 bytes of each message
represent the message length
This commit is contained in:
parent
0145ff15cb
commit
46c32a90bb
|
@ -12,6 +12,12 @@
|
||||||
(let ((file (open-input-file "pizza_list.json")))
|
(let ((file (open-input-file "pizza_list.json")))
|
||||||
(read-json file)))
|
(read-json file)))
|
||||||
|
|
||||||
|
; Send the pizza list as a JSON, prepending it with 4 bytes that contain the list length
|
||||||
|
(define (send-pizzas-list output)
|
||||||
|
(let ((pizzas-list (get-pizzas-list)))
|
||||||
|
(write-bytes (integer->integer-bytes (bytes-length (jsexpr->bytes pizzas-list)) 4 #f) output)
|
||||||
|
(write-json pizzas-list output)))
|
||||||
|
|
||||||
; Print the to-print string on the printer
|
; Print the to-print string on the printer
|
||||||
; TODO add synchronization to avoid race conditions
|
; TODO add synchronization to avoid race conditions
|
||||||
(define (printer-print to-print)
|
(define (printer-print to-print)
|
||||||
|
@ -33,20 +39,18 @@
|
||||||
(case (hash-ref parsed-json 'command)
|
(case (hash-ref parsed-json 'command)
|
||||||
(("print") (printer-print (hash-ref parsed-json 'text)))
|
(("print") (printer-print (hash-ref parsed-json 'text)))
|
||||||
(("pizza") (printer-print (format-pizza (hash-ref parsed-json 'pizzas))))
|
(("pizza") (printer-print (format-pizza (hash-ref parsed-json 'pizzas))))
|
||||||
(("get-pizzas") (write-json (get-pizzas-list) output)))))
|
(("get-pizzas") (send-pizzas-list output))
|
||||||
|
(else (displayln "Unknown command")))))
|
||||||
|
|
||||||
; Execute the command specified in the JSON
|
; Parse the JSON and execute the command specified in it
|
||||||
|
;
|
||||||
|
; Each message starts with the length of the JSON object, put into the first 4 bytes
|
||||||
(define (execute-commands input output)
|
(define (execute-commands input output)
|
||||||
(let ((message ""))
|
; read the first 4 bytes, little-endian, unsigned
|
||||||
(let loop-until-eof ((str (read-string 1 input)))
|
(let ((message-length (integer-bytes->integer (read-bytes 4 input) #f)))
|
||||||
(if (eof-object? str)
|
(parse-json (bytes->string/utf-8 (read-bytes message-length input)) output)
|
||||||
(begin
|
(close-input-port input)
|
||||||
(parse-json message output)
|
(close-output-port output)))
|
||||||
(close-input-port input)
|
|
||||||
(close-output-port output))
|
|
||||||
(begin
|
|
||||||
(set! message (string-append message str))
|
|
||||||
(loop-until-eof (read-string 1 input)))))))
|
|
||||||
|
|
||||||
; Wait on a port and spawn new threads on each connection
|
; Wait on a port and spawn new threads on each connection
|
||||||
(define (wait-for-connection)
|
(define (wait-for-connection)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user