Networking and Web Applications

This chapter moves from a single program to programs that talk to each other. It starts with a raw TCP server and client built on Lwt sockets, in source-code/client_server/. Then it builds two web applications on Dream, a modern OCaml web framework: a “web view” app with a JavaScript bridge, in source-code/webview/, and a chat app that forwards prompts to the Google Gemini API, in source-code/webchat/.

A TCP Server and Client

The server in server.ml reverses every chunk of bytes a client sends. It uses Lwt_unix, which is the standard Unix socket calls in Lwt form, so recv and send map straight onto the system calls. First, the per-connection loop:

1 let rec reverse_loop sock =
2   let buf = Bytes.create 4096 in
3   let* n = Lwt_unix.recv sock buf 0 4096 [] in
4   if n = 0 then Lwt.return_unit
5   else
6     let* _ = Lwt_unix.send sock (reverse_bytes buf n) 0 n [] in
7     reverse_loop sock

Lwt_unix.recv reads up to 4096 bytes into a buffer and returns how many it got. A count of zero means the client closed the connection, so the loop ends. Otherwise it sends back the reversed bytes and loops. The setup opens a socket, allows address reuse, binds to the loopback address, and accepts connections in a loop:

 1 let sock = Lwt_unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
 2 Lwt_unix.setsockopt sock Unix.SO_REUSEADDR true;
 3 let addr = Unix.(ADDR_INET (inet_addr_loopback, 3000)) in
 4 let* () = Lwt_unix.bind sock addr in
 5 Lwt_unix.listen sock 10;
 6 ...
 7 let rec accept_loop () =
 8   let* client, caddr = Lwt_unix.accept sock in
 9   Printf.printf "Connection from %s\n%!" (string_of_addr caddr);
10   Lwt.async (fun () ->
11       Lwt.finalize
12         (fun () -> reverse_loop client)
13         (fun () -> Lwt_unix.close client));
14   accept_loop ()

Two Lwt functions handle concurrency. Lwt.async starts a lightweight thread for each client and moves on, so one slow client never blocks the accept loop. Lwt.finalize runs its second function no matter how the first ends, so the client socket always closes. Binding to inet_addr_loopback keeps the server on 127.0.0.1, not exposed to the network.

The client in client.ml is the mirror image: connect, send a message, print the reply:

 1 let sock = Lwt_unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
 2 let addr = Unix.(ADDR_INET (inet_addr_loopback, 3000)) in
 3 let* () = Lwt_unix.connect sock addr in
 4 print_endline "Connection established to 127.0.0.1:3000";
 5 let msg = Bytes.of_string "test123" in
 6 let* _ = Lwt_unix.send sock msg 0 (Bytes.length msg) [] in
 7 let buf = Bytes.create 100 in
 8 let* n = Lwt_unix.recv sock buf 0 100 [] in
 9 ...
10 Printf.printf "Response: %s\n" (Bytes.sub_string buf 0 n);

Run the server in one terminal and the client in another:

1 cd source-code/client_server
2 dune exec ./server.exe    # terminal 1
3 dune exec ./client.exe    # terminal 2

The client sends test123 and prints Response: 321tset, the reversed bytes.

Web Applications with Dream

Dream serves HTTP with a simple shape: you build a pipeline of Dream.run, some middleware like Dream.logger, and a Dream.router that maps routes to handlers. A handler takes a request and returns a response promise. The next two examples use this shape.

One OCaml detail makes web code pleasant: quoted string literals. Writing {html|...|html} gives you a string delimited by |html} instead of double quotes, so you can paste HTML or JavaScript inside with no escaping. The examples use {html|...|html}, {js|...|js}, and {page|...|page} to hold their front-end code.

A Web View With a JavaScript Bridge

The webview example recreates a native “web view” idea as a Dream app. A browser page calls backend handlers through a small JavaScript shim that POSTs to the server. The host, in lib/webview.ml, keeps a table of named handlers, each a function from a JSON payload to a JSON result:

 1 type app = { handlers : (string, Yojson.Safe.t -> Yojson.Safe.t) Hashtbl.t }
 2 
 3 let create () = { handlers = Hashtbl.create 16 }
 4 let register app command handler = Hashtbl.replace app.handlers command handler
 5 
 6 let dispatch app command payload =
 7   match Hashtbl.find_opt app.handlers command with
 8   | Some h -> (
 9     try h payload
10     with e -> `Assoc [ ("error", `String (Printexc.to_string e)) ])
11   | None -> `Assoc [ ("error", `String ("Unknown command: " ^ command)) ]

register adds a handler under a command name. dispatch looks one up and runs it, turning an unknown command or a thrown exception into a JSON error object, so a bad request never crashes the server. The browser shim, served at /bridge.js, gives the page one function that POSTs to /bridge/<command>:

 1 let bridge_js =
 2   {js|window.webkit_haskell = {
 3   invoke: async function (command, payload) {
 4     const r = await fetch('/bridge/' + command, {
 5       method: 'POST',
 6       headers: { 'Content-Type': 'application/json' },
 7       body: JSON.stringify(payload || {})
 8     });
 9     return await r.json();
10   }
11 };
12 |js}

The router wires three routes: the page, the bridge script, and the POST endpoint that dispatches to a handler:

 1 let run ?(port = 8080) app ~page =
 2   Dream.run ~interface:"127.0.0.1" ~port
 3   @@ Dream.logger
 4   @@ Dream.router
 5        [ Dream.get "/" (fun _ -> Dream.html page);
 6          Dream.get "/bridge.js" (fun _ ->
 7              Dream.respond
 8                ~headers:[ ("Content-Type", "application/javascript") ]
 9                bridge_js);
10          Dream.post "/bridge/:command" (fun req ->
11              let command = Dream.param req "command" in
12              let* body = Dream.body req in
13              let payload = try Yojson.Safe.from_string body with _ -> `Null in
14              Dream.json (Yojson.Safe.to_string (dispatch app command payload)))
15        ]

The route /bridge/:command has a path parameter, read with Dream.param req "command". The handler reads the request body, parses it as JSON, and returns the dispatch result as JSON. The @@ operators chain the pipeline: run wraps logger wraps router.

The counter app in bin/counter.ml supplies the page and the handlers. It keeps the count in a mutable ref and registers one handler per button:

1 let app = Webview.create () in
2 let count = ref 0 in
3 let counted () = `Assoc [ ("count", `Int !count) ] in
4 Webview.register app "increment" (fun _ -> incr count; counted ());
5 Webview.register app "decrement" (fun _ -> decr count; counted ());
6 Webview.register app "reset" (fun _ -> count := 0; counted ());
7 Webview.register app "get-count" (fun _ -> counted ());
8 Webview.register app "get-system-info" (fun _ -> ...);

Each handler updates the count and returns it as JSON. The page’s JavaScript calls window.webkit_haskell.invoke('increment', {}) when you click a button, and updates the display with the returned count. Run it and open the printed URL:

1 cd source-code/webview
2 dune exec ./bin/counter.exe   # then open http://127.0.0.1:8080/

A Chat App Backed by Gemini

The webchat example serves a chat page and forwards each prompt to the Gemini API. It splits into a pure codec, in lib/chat.ml, and the server, in bin/main.ml. Keeping the codec pure lets the tests run with no server and no API key.

The codec builds the Gemini request body and reads the response text. Both are plain Yojson:

 1 let gemini_request prompt =
 2   `Assoc
 3     [ ( "contents",
 4         `List
 5           [ `Assoc [ ("parts", `List [ `Assoc [ ("text", `String prompt) ] ]) ] ] );
 6       ( "generationConfig",
 7         `Assoc
 8           [ ("temperature", `Float 0.1); ("maxOutputTokens", `Int 800) ] )
 9     ]
10 
11 let text_of_json json =
12   let open Yojson.Safe.Util in
13   match json |> member "candidates" |> to_list with
14   | candidate :: _ -> (
15     match candidate |> member "content" |> member "parts" |> to_list with
16     | part :: _ -> Ok (part |> member "text" |> to_string)
17     | [] -> Error "No content in response")
18   | [] -> Error "No candidates in response"
19   | exception _ -> Error "Failed to parse Gemini response"

text_of_json returns a result, and its final exception _ case turns a malformed response into an Error rather than a crash. The codec also names the model once, let default_model = "gemini-3.5-flash", and endpoint_for builds the request URL from it, so the server’s endpoint is Chat.endpoint_for Chat.default_model. The server posts the request to Gemini and returns the reply as JSON:

 1 let call_gemini ~api_key prompt =
 2   let body = Yojson.Safe.to_string (Chat.gemini_request prompt) in
 3   let headers =
 4     Cohttp.Header.of_list
 5       [ ("Content-Type", "application/json"); ("x-goog-api-key", api_key) ]
 6   in
 7   Lwt.catch
 8     (fun () ->
 9       let* resp, rbody =
10         Cohttp_lwt_unix.Client.post ~headers
11           ~body:(Cohttp_lwt.Body.of_string body)
12           (Uri.of_string endpoint)
13       in
14       let* s = Cohttp_lwt.Body.to_string rbody in
15       let code = Cohttp.Code.code_of_status (Cohttp.Response.status resp) in
16       if code = 200 then Lwt.return (Chat.text_of_json (Yojson.Safe.from_string s))
17       else Lwt.return (Error (Printf.sprintf "API request failed with status %d" code)))
18     (fun exn -> Lwt.return (Error ("Network error: " ^ Printexc.to_string exn)))

The main function reads the API key from the environment, exits with a clear message if it is missing, and otherwise starts a Dream server with two routes: the page, and a /chat POST that calls Gemini and returns the text:

1 Dream.post "/chat" (fun request ->
2     let* body = Dream.body request in
3     let* result = call_gemini ~api_key (Chat.prompt_of_body body) in
4     match result with
5     | Ok text ->
6       Dream.json (Yojson.Safe.to_string (`Assoc [ ("text", `String text) ]))
7     | Error e ->
8       Dream.json ~status:`Internal_Server_Error
9         (Yojson.Safe.to_string (`Assoc [ ("error", `String e) ])))

Set the key and run it:

1 cd source-code/webchat
2 export GOOGLE_API_KEY=your-key-here
3 dune exec ./bin/main.exe       # then open http://127.0.0.1:3000/
4 dune runtest                   # codec tests, no key needed

Type a prompt in the page and the reply appears below it. The next chapter covers the Gemini API and two other model APIs from the command line, using the same request-and-decode pattern you just saw in the chat codec.