I’m new to OCaml and have been struggling to set up a simple TCP server that stays open and can be killed or interrupted with Ctrl-C. Here's where I'm at with
Lwt_io.establish_server_with_client_address`:
let establish_server port f =
(* Create a new socket *)
let default_protocol = 0 in
let socket = Lwt_unix.socket PF_INET SOCK_STREAM default_protocol in
let _ = Lwt_unix.setsockopt socket SO_REUSEADDR true in
(* Create a socket address *)
let host = Unix.inet_addr_loopback in
let addr = Unix.ADDR_INET (host, port) in
(* Start server *)
let max_pending_requests = 10 in
let server = Lwt_io.establish_server_with_client_address
~backlog:max_pending_requests
~fd:socket
addr
f; in
server
let service _client_address (_in_channel, _out_channel) =
let%lwt _ = Lwt_io.eprintf "TODO ;)\n%!"; in
Lwt.return ()
let () =
Lwt_main.run begin
let port = 8080 in
let%lwt _ = establish_server port service; in
(* ???
Lwt.return () // <-- This will close immediately without keeping the server open
fst (Lwt.task ()) // <-- this can't be cancelled with Ctrl-C
*)
end