establish_server_with_client_address listen_address f
creates a server which listens for incoming connections on listen_address
. When a client makes a new connection, it is passed to f
: more precisely, the server calls
f client_address (in_channel, out_channel)
where client_address
is the address (peer name) of the new client, and in_channel
and out_channel
are two channels wrapping the socket for communicating with that client.
The server does not block waiting for f
to complete: it concurrently tries to accept more client connections while f
is handling the client.
When the promise returned by f
completes (i.e., f
is done handling the client), establish_server_with_client_address
automatically closes in_channel
and out_channel
. This is a default behavior that is useful for simple cases, but for a robust application you should explicitly close these channels yourself, and handle any exceptions. If the channels are still open when f
completes, and their automatic closing raises an exception, establish_server_with_client_address
treats it as an unhandled exception reaching the top level of the application: it passes that exception to Lwt.async_exception_hook
, the default behavior of which is to print the exception and terminate your process.
Automatic closing can be completely disabled by passing ~no_close:true
.
Similarly, if f
raises an exception (or the promise it returns fails with an exception), establish_server_with_client_address
can do nothing with that exception, except pass it to Lwt.async_exception_hook
.
~fd
can be specified to use an existing file descriptor for listening. Otherwise, a fresh socket is created internally.
~backlog
is the argument passed to Lwt_unix.listen
.
The returned promise (a server Lwt.t
) resolves when the server has just started listening on listen_address
: right after the internal call to listen
, and right before the first internal call to accept
.