8000
Skip to content

Add router/dealer server to examples #21

@phoe

Description

@phoe

I have created a very rough example of an asynchronous N-to-1 server using dealer/router sockets. If my code isn't complete beginner trash, it might be good to add it to the examples section.

;; modified from pzmq examples

(defun hwclient (&optional (server-address "tcp://localhost:5555"))
  "Translation of http://zguide.zeromq.org/c:hwclient updated for ZMQ 3.
Includes some parameters in with-* macros to demonstrate syntax."
  (pzmq:with-context (ctx :max-sockets 10)
    (pzmq:with-socket (requester ctx) (:dealer :affinity 3 :linger 100)
      ;; linger is important in case of (keyboard) interrupt;
      ;; see http://api.zeromq.org/3-3:zmq-ctx-destroy
      (pzmq:connect requester server-address)
      (dotimes (i 10)
        (format t "Sending Hello ~d...~%" i)
        (pzmq:send requester "Hello!" :dontwait nil)
        (write-string "Receiving... ")
        (write-line (pzmq:recv-string requester))))))

(defun hwserver (&optional (listen-address "tcp://*:5555"))
  "Translation of http://zguide.zeromq.org/c:hwserver updated for ZMQ 3. "
  (pzmq:with-context nil ; use *default-context*
    (pzmq:with-socket responder :router
      (pzmq:bind responder listen-address)
      (dotimes (i 10)
        (pzmq:with-message msg
          (pzmq:msg-recv msg responder)
          (let ((identity (cffi:foreign-array-to-lisp
                           (pzmq:msg-data msg) `(:array :unsigned-char 5)
                           :element-type '(unsigned-byte 8))))
            (print identity)
            (pzmq:msg-recv msg responder)
            (let ((hello (cffi:foreign-string-to-lisp
                          (pzmq:msg-data msg)
                          :count (pzmq:msg-size msg))))
              (write-line hello))
            (cffi:with-pointer-to-vector-data (pointer identity)
              (pzmq:send responder pointer :len 5 :sndmore t))
            (pzmq:send responder "World!")
            (write-line "Sent response...")))))))

;; run (hwclient) and (hwserver) on two different Lisp threads/instances on the same machine

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0