issuu/ocaml-zmq

would it be possible to have an example of polling ?

UnixJunkie opened this issue · 7 comments

Let's say a server has two sockets: a rep socket and a pull socket, how to poll on them?

Wrapping the whole thing in Lwt or Async is an option as well. That's only really effective if you're application fits with Lwt/Async.

@hcarty I will stay away from Lwt/Async as long as I can (hopefully forever). :)

@whitequark unfortunately, types are only an incomplete specification.
I would get started faster with an example, anyway, I will try later to use polling.

Heres a small example on how to poll (receive) on a list of sockets and do a callback with reveiced data:

let recv (scl: ('a ZMQ.Socket.t * (string -> unit)) list) : unit -> unit =
  let set =
    scl
    |> List.map (fun (socket, _callback) -> socket, ZMQ.Poll.In)
    |> Array.of_list
    |> ZMQ.Poll.mask_of
  in

  fun () ->
    let poll_set = ZMQ.Poll.poll set |> Array.to_list in
    List.iter2 (fun (socket, callback) ->
      function
      | Some ZMQ.Poll.In -> callback (ZMQ.Socket.recv socket)
      | Some _ -> raise Not_found 
      | None -> ()
    ) scl poll_set

let () =
  let ctx = ZMQ.Context.create () in
  let rep = ZMQ.Socket.(create ctx rep) in
  let pull = ZMQ.Socket.(create ctx pull) in

  recv [(rep, Printf.printf "Recv rep: %s");
        (pull, Printf.printf "Rect pull: %s")] ()

Thanks a lot!

Updated the example a bit, and marking this as done.