Skip to content

Instantly share code, notes, and snippets.

@zehnpaard
Created May 9, 2020 19:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zehnpaard/da00cdce9e94c73183a2df1d9e8758a5 to your computer and use it in GitHub Desktop.
Save zehnpaard/da00cdce9e94c73183a2df1d9e8758a5 to your computer and use it in GitHub Desktop.
Minimal Lwt multi-client echo server based on https://www.baturin.org/code/lwt-counter-server/
(executable
(name server)
(libraries lwt.unix))
open Lwt
open Lwt.Syntax
let rec request_response_loop ic oc =
let* msg = Lwt_io.read_line_opt ic in
match msg with
| Some text ->
let* () = Lwt_io.write_line oc text in
request_response_loop ic oc
| None -> return ()
let accept_conn conn_fd =
let ic = Lwt_io.of_fd ~mode:Lwt_io.Input conn_fd in
let oc = Lwt_io.of_fd ~mode:Lwt_io.Output conn_fd in
request_response_loop ic oc
let rec server_loop sock =
let* conn_fd, _ = Lwt_unix.accept sock in
async (fun () -> accept_conn conn_fd);
server_loop sock
let () =
let open Lwt_unix in
let sock = socket PF_INET SOCK_STREAM 0 in
let sock_addr = ADDR_INET(Unix.inet_addr_loopback, 9000) in
async (fun () -> bind sock sock_addr);
listen sock 10;
Lwt_main.run @@ server_loop sock
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment