mirror of
https://github.com/c-cube/tiny_httpd.git
synced 2025-12-06 03:05:29 -05:00
add some example programs to exercize server-sent events
This commit is contained in:
parent
17d8f37c93
commit
ce552cafdd
3 changed files with 74 additions and 0 deletions
10
examples/dune
Normal file
10
examples/dune
Normal file
|
|
@ -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))
|
||||
28
examples/sse_client.ml
Normal file
28
examples/sse_client.ml
Normal file
|
|
@ -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!@."
|
||||
36
examples/sse_clock.ml
Normal file
36
examples/sse_clock.ml
Normal file
|
|
@ -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
|
||||
|
||||
|
||||
Loading…
Add table
Reference in a new issue