I want to send a message via TCP to remote server. This message consists of a few fields, some fields are sting, some are number. My old way is to pack one field and then send it. e.g.
(define (send-message type content)
;; send SOH
(unless (net-send (self 4) SOH) (throw-error (string "send soh failed: " (net-error))))
;; send length
(unless (net-send (self 4) (hex-str (+ 10 (length content)) 4)) (throw-error (string "send length failed: " (net-error))))
;; send type
(unless (net-send (self 4) type) (throw-error (string "send type failed: " (net-error))))
;; send content
(unless (net-send (self 4) content) (throw-error (string "send content failed: " (net-error))))
;; send checksum
(let (checksum-value (cal-checksum (total2 (append type content))))
(unless (net-send (self 4) (hex-str checksum-value 2)) (throw-error (string "send checksumfailed: " (net-error)))))
;; send ETX
(unless (net-send (self 4) ETX) (throw-error (string "send etx failed: " (net-error)))))
But I want to pack all fields in one string buffer and send them one time. How to do this?
Got it. just use (string ) to contruct it.
(define (send-message type content)
(letn ((checksum-value (hex-str (cal-checksum (total2 (append type content))) 2))
(str-buffer (string (pack "b" 1) (format "%s%s%s%s" (hex-str (+ 10 (length content)) 4) type content checksum-value) (pack "b" 3))))
(let (r (net-send (self 4) str-buffer))
(if r
(log (format "sent message succeeded, size is: %llu" r))
(throw-error (string "send message failed: " (net-error)))))
))