Help debug ocaml async websocket echo client

Hey, I am connecting a client to the web sockets org echo server. This is my code

open Core
open Async

let send_and_receive () =
  let uri = Uri.of_string "wss://echo.websocket.org" in

  print_endline "connecting";
  let%bind _response, websocket =
    Cohttp_async_websocket.Client.create uri >>| Or_error.ok_exn
  in
  let reader, writer = Websocket.pipes websocket in

  print_endline "writing";
  let%bind () = Pipe.write writer "lol omg wut" in

  print_endline "reading";
  let%bind () =
    match%bind Pipe.read reader with
    | `Eof ->
        print_endline "Eof";
        return ()
    | `Ok s ->
        print_endline "Ok";
        let prefix = Time_ns_unix.now () |> Time_ns_unix.to_string in
        let s = prefix ^ " " ^ s in
        print_endline s;
        return ()
  in
  return ()

let () =
  Command.async ~summary:"Websocket client sample"
    (Command.Param.return send_and_receive)
  |> Command_unix.run


This is the error I am getting

connecting
(monitor.ml.Error
 ("attempt to use closed writer"
  ((file_descr 8) (info (writer app_to_ssl)) (kind Fifo)))
 ("Called from Base__Error.raise_s in file \"src/error.ml\", line 10, characters 26-47"
  "Called from Async_unix__Writer0.Checked_writes.write in file \"src/writer0.ml\" (inlined), line 1648, characters 4-22"
  "Called from Cohttp_async__Io.write.(fun) in file \"cohttp-async/src/io.ml\", line 96, characters 6-25"
  "Called from Cohttp__Request.Make.write_header in file \"cohttp/src/request.ml\", line 224, characters 4-24"
  "Called from Cohttp_async_websocket.Client.create.(fun) in file \"src/cohttp_async_websocket.ml\", line 607, characters 23-59"))

Can you please help me debug this one?

Your code succeeds for me with this addition to the Client.createcall:

~force_ssl_overriding_SNI_hostname:"echo.websocket.org"

ouput:

connecting                          
writing
reading
Ok
2026-02-06 21:00:20.956986126-06:00 Request served by ...

But my guess is that this endpoint is relatively strict and that the library’s subtly wrong - something like trying to write without first reading.

Thank you, Julian, this works :slight_smile: #resolved