Skip to content

Instantly share code, notes, and snippets.

@greenbagels
Created May 17, 2022 03:04
Show Gist options
  • Save greenbagels/256f34734628c6d93f37bfd58ec2f095 to your computer and use it in GitHub Desktop.
Save greenbagels/256f34734628c6d93f37bfd58ec2f095 to your computer and use it in GitHub Desktop.
let handle_ws_message msg =
Lwt_io.printf "> %s\n" msg
let connect uri =
let%lwt endp = Resolver_lwt.resolve_uri ~uri Resolver_lwt_unix.system in
let ctx = Lazy.force Conduit_lwt_unix.default_ctx in
let%lwt client = Conduit_lwt_unix.endp_to_client ~ctx endp in
let%lwt conn = Websocket_lwt_unix.connect ~ctx client uri in
let rec handle_ws_input msg_content =
let%lwt frame = Websocket_lwt_unix.read conn in
let open Websocket in
match frame with
| {Frame.opcode = Ping; _} ->
let%lwt () = Websocket_lwt_unix.write conn
(Websocket.Frame.create ~opcode:Pong ()) in
handle_ws_input msg_content
| {Frame.opcode = Pong; _} ->
handle_ws_input msg_content
| {Frame.opcode = Text; Frame.final = true; content; _}
| {Frame.opcode = Binary; Frame.final = true; content; _} ->
handle_ws_message (msg_content ^ content);
handle_ws_input ""
| {Frame.opcode = Text; Frame.final = false; content; _}
| {Frame.opcode = Binary; Frame.final = false; content; _} ->
handle_ws_input (msg_content ^ content)
| _ -> Websocket_lwt_unix.close_transport conn in
handle_ws_input ""
(*
* File "test.ml", line 23, characters 16-57:
* 23 | handle_ws_message (msg_content ^ content);
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* Warning 10 [non-unit-statement]: this expression should have type unit.
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment