diff --git a/examples/dune b/examples/dune new file mode 100644 index 00000000..985480d9 --- /dev/null +++ b/examples/dune @@ -0,0 +1,10 @@ + +(executable + (name sse_clock) + (modules sse_clock) + (libraries tiny_httpd unix ptime ptime.clock.os)) + +(executable + (name sse_client) + (modules sse_client) + (libraries unix)) diff --git a/examples/sse_client.ml b/examples/sse_client.ml new file mode 100644 index 00000000..3e7ef6f5 --- /dev/null +++ b/examples/sse_client.ml @@ -0,0 +1,28 @@ +let addr = ref "127.0.0.1" +let port = ref 8080 + +let bufsize = 1024 + +let () = + Arg.parse (Arg.align [ + "-p", Arg.Set_int port, " port to connect to"; + ]) (fun s -> addr := s) "sse_client [opt]* [addr]?"; + + Format.printf "connect to %s:%d@." !addr !port; + let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in + Unix.connect sock (Unix.ADDR_INET (Unix.inet_addr_of_string !addr, !port)); + Unix.setsockopt sock Unix.TCP_NODELAY false; + + let ic = Unix.in_channel_of_descr sock in + let oc = Unix.out_channel_of_descr sock in + output_string oc "GET /clock HTTP/1.1\r\nHost: localhost\r\n\r\n"; + flush oc; + + let continue = ref true in + let buf = Bytes.create bufsize in + while !continue do + let n = input ic buf 0 bufsize in + if n=0 then continue := false; + output stdout buf 0 n; flush stdout + done; + Format.printf "bye!@." diff --git a/examples/sse_clock.ml b/examples/sse_clock.ml new file mode 100644 index 00000000..442ef088 --- /dev/null +++ b/examples/sse_clock.ml @@ -0,0 +1,36 @@ + +(* serves a stream of clock events *) + +module S = Tiny_httpd + +let port = ref 8080 + +let () = + Arg.parse (Arg.align [ + "-p", Arg.Set_int port, " port to listen on"; + "--debug", Arg.Bool S._enable_debug, " toggle debug"; + ]) (fun _ -> ()) "sse_clock [opt*]"; + let server = S.create ~port:!port () in + + S.add_route_server_sent_handler server S.Route.(exact "clock" @/ return) + (fun _req (module EV : S.SERVER_SENT_GENERATOR) -> + S._debug (fun k->k"new connection"); + let tick = ref true in + while true do + let now = Ptime_clock.now() in + S._debug (fun k->k"send clock ev %s" (Format.asprintf "%a" Ptime.pp now)); + EV.send_event ~event:(if !tick then "tick" else "tock") + ~data:(Ptime.to_rfc3339 now) (); + tick := not !tick; + + Unix.sleepf 1.0; + done; + ); + + Printf.printf "listening on http://localhost:%d/\n%!" (S.port server); + match S.run server with + | Ok () -> () + | Error e -> + Printf.eprintf "error: %s\n%!" (Printexc.to_string e); exit 1 + +