flesh/portal/test/js/websockets_hello.ml

32 lines
1.1 KiB
OCaml

open Lwt.Syntax
open Js_of_ocaml
(* https://stackoverflow.com/questions/34929382/what-are-the-differences-between-lwt-async-and-lwt-main-run-on-ocaml-node-js *)
let rec run t =
let next_tick (_callback : unit -> unit) =
Js.Unsafe.(fun_call
(js_expr "process.nextTick")
[| inject (Js.wrap_callback _callback) |])
in Lwt.wakeup_paused ();
match Lwt.poll t with
| Some x -> x
| None ->
if Lwt.paused_count () > 0
then next_tick (fun () -> run t)
else ()
let () =
run @@
let* ws = Portal_ws.ws_endpoint "squarebowl.club" in
let stream, push =
(* Echo is a websocket that... echoes you stuff. *)
Portal_ws.ws_stream ws in
push (Some "malformed");
let+ stanzas = stream
|> Lwt_stream.map
(fun stanza ->
match stanza with
| {|<close xmlns='urn:ietf:params:xml:ns:xmpp-framing'/>|} -> push None; stanza
| stanza -> stanza)
|> Lwt_stream.to_list
in List.map (fun x -> " >>> " ^ x) stanzas |> String.concat "\n" |> print_endline