Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add router/dealer server to examples #21

Open
phoe opened this issue May 24, 2019 · 0 comments
Open

Add router/dealer server to examples #21

phoe opened this issue May 24, 2019 · 0 comments

Comments

@phoe
Copy link
Contributor

phoe commented May 24, 2019

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant