2 (** raised when a client timeouts *)
7 (** if timeout is given (Some _) @return a new callback which establish
8 timeout_callback as callback for signal Sys.sigalrm and register an alarm
9 (expiring after timeout seconds) before invoking the real callback given. If
10 timeout is None, callback is returned unchanged. *)
11 let wrap_callback_w_timeout ~callback ~timeout ~timeout_callback =
14 | Some timeout -> (* wrap callback setting an handler for ALRM signal and an
15 alarm that ring after timeout seconds *)
16 (fun inchan outchan ->
17 ignore (Sys.signal Sys.sigalrm (Sys.Signal_handle ~timeout_callback));
18 ignore (Unix.alarm timeout);
19 callback inchan outchan)
21 (** tcp_server which doesn't fork, requests are server sequentially and in the
22 same address space of the calling process *)
23 let simple ~sockaddr ~timeout callback =
24 let suck = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
25 Unix.setsockopt suck Unix.SO_REUSEADDR true;
26 Unix.bind suck sockaddr;
27 Unix.listen suck backlog;
28 let timeout_callback signo =
29 if signo = Sys.sigalrm then
32 let callback = wrap_callback_w_timeout ~callback ~timeout ~timeout_callback in
34 let (client, _) = Unix.accept suck in
35 (* client is now connected *)
36 let (inchan, outchan) =
37 (Unix.in_channel_of_descr client, Unix.out_channel_of_descr client)
40 callback inchan outchan;
41 ignore (Unix.alarm 0) (* reset alarm *)
43 close_out outchan (* this close also inchan, because socket is the same *)
46 (** tcp_server which use Unix.establish_server which in turn forks a child for
48 let ocaml_builtin ~sockaddr ~timeout callback =
49 let timeout_callback signo =
50 if signo = Sys.sigalrm then
54 (wrap_callback_w_timeout ~callback ~timeout ~timeout_callback)
57 (* TODO this is a cut-and-paste from 'simple' *)
58 (** tcp_server which creates a new thread for each request to be served *)
59 let thread ~sockaddr ~timeout callback =
60 let suck = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
61 Unix.setsockopt suck Unix.SO_REUSEADDR true;
62 Unix.bind suck sockaddr;
63 Unix.listen suck backlog;
64 let timeout_callback signo =
65 if signo = Sys.sigalrm then
68 let callback = wrap_callback_w_timeout ~callback ~timeout ~timeout_callback in
74 | Timeout -> close_out o
80 let (client, _) = Unix.accept suck in
81 (* client is now connected *)
82 let (inchan, outchan) =
83 (Unix.in_channel_of_descr client, Unix.out_channel_of_descr client)
85 ignore (Thread.create callback (inchan, outchan));