From 46c32a90bb45a7a34a2ae20f805f1d1fd30d1b54 Mon Sep 17 00:00:00 2001 From: palo Date: Sat, 28 Oct 2023 00:01:05 +0200 Subject: [PATCH] Changed the communication protocol: the first 4 bytes of each message represent the message length --- scontrini.rkt | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/scontrini.rkt b/scontrini.rkt index 78a425b..e753502 100644 --- a/scontrini.rkt +++ b/scontrini.rkt @@ -12,6 +12,12 @@ (let ((file (open-input-file "pizza_list.json"))) (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 ; TODO add synchronization to avoid race conditions (define (printer-print to-print) @@ -33,20 +39,18 @@ (case (hash-ref parsed-json 'command) (("print") (printer-print (hash-ref parsed-json 'text))) (("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) - (let ((message "")) - (let loop-until-eof ((str (read-string 1 input))) - (if (eof-object? str) - (begin - (parse-json message output) - (close-input-port input) - (close-output-port output)) - (begin - (set! message (string-append message str)) - (loop-until-eof (read-string 1 input))))))) + ; read the first 4 bytes, little-endian, unsigned + (let ((message-length (integer-bytes->integer (read-bytes 4 input) #f))) + (parse-json (bytes->string/utf-8 (read-bytes message-length input)) output) + (close-input-port input) + (close-output-port output))) ; Wait on a port and spawn new threads on each connection (define (wait-for-connection)