Skip to content

Instantly share code, notes, and snippets.

@greenbagels
Created May 20, 2022 21:46
Show Gist options
  • Save greenbagels/0ad0ea1db2c2fde829c8f870218403cb to your computer and use it in GitHub Desktop.
Save greenbagels/0ad0ea1db2c2fde829c8f870218403cb to your computer and use it in GitHub Desktop.
let rec start_heartbeat_loop conn interval =
let open Websocket_lwt_unix in
let open Websocket in
match !recv_hb_ack with
| true -> let () = (recv_hb_ack := false) in
let%lwt () = Lwt_io.printf "Sleeping for %f seconds!\n" interval in
let%lwt () = Lwt_unix.sleep interval in
let (json_resp : Yojson.Safe.t) = match !last_seq with
| Some n -> `Assoc [ ("op", `Int 1); ("d", `Int n) ]
| None -> `Assoc [ ("op", `Int 1); ("d", `Null) ] in
let content = Yojson.Safe.pretty_to_string json_resp in
let%lwt () = write conn (Frame.create ~content ()) in
let%lwt () = Lwt_io.printf "Sending heartbeat...\n" in
start_heartbeat_loop conn interval
| false -> write conn (Frame.create ~opcode:Close ())
let handle_ws_message conn msg token =
let open Yojson.Safe in
let%lwt () = Lwt_io.printf "> %s\n" msg in
let msg_json = from_string msg in
let opcode = msg_json |> Util.member "op" |> Util.to_int in
match opcode with
| 10 -> let interval_ms = msg_json |> Util.member "d" |> Util.member "heartbeat_interval" |> Util.to_int in
let interval_sec = (float_of_int interval_ms) /. 1000. in
start_heartbeat_loop conn interval_sec
| _ -> Lwt_io.printf "Unsupported opcode found!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment