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")))
|
||||
(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)
|
||||
; 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))
|
||||
(begin
|
||||
(set! message (string-append message str))
|
||||
(loop-until-eof (read-string 1 input)))))))
|
||||
(close-output-port output)))
|
||||
|
||||
; Wait on a port and spawn new threads on each connection
|
||||
(define (wait-for-connection)
|
||||
|
|
Loading…
Reference in New Issue
Block a user