Skip to content

Instantly share code, notes, and snippets.

@Et7f3
Created August 27, 2019 15:22
Show Gist options
  • Save Et7f3/47390b33fe780225476129a08000b49c to your computer and use it in GitHub Desktop.
Save Et7f3/47390b33fe780225476129a08000b49c to your computer and use it in GitHub Desktop.
OCaml-websocket+opium
(executable
(name host_web)
(libraries opium websocket-lwt-unix.cohttp))
open Opium.Std
open Lwt.Infix
open Websocket
let src = Logs.Src.create "websocket.upgrade_connection"
let ws = all "/ws" (fun req ->
let body = Request.body req
and req = Request.request req in
let open Frame in
Logs_lwt.app ~src (fun m -> m "[PATH] /ws") >>= fun () ->
Cohttp_lwt.Body.drain_body body >>= fun () ->
Websocket_cohttp_lwt.upgrade_connection
req begin fun { opcode ; content ; _ } ->
match opcode with
| Opcode.Close ->
Logs.app ~src (fun m -> m "[RECV] CLOSE")
| _ ->
Logs.app ~src (fun m -> m "[RECV] %s" content)
end >>= fun (resp, frames_out_fn) ->
(* send a message to the client every second *)
let num_ref = ref 10 in
let rec go () =
if !num_ref = 0 then
Logs_lwt.app ~src (fun m -> m "[INFO] Test done")
else
let msg = Printf.sprintf "-> Ping %d" !num_ref in
Logs_lwt.app ~src (fun m -> m "[SEND] %s" msg) >>= fun () ->
Lwt.wrap1 frames_out_fn @@
Some (Frame.create ~content:msg ()) >>= fun () ->
decr num_ref ;
Lwt_unix.sleep 1. >>=
go
in
Lwt.async go ;
let resp =
match resp with
| `Expert (resp, _) ->
let () = print_endline "expert" in
Response.create ~headers:resp.headers ~code:resp.status ()
| `Response (resp, body) ->
let () = print_endline "response" in
Response.create ~body ~headers:resp.headers ~code:resp.status ()
in Lwt.return resp)
let a =
App.empty
|> ws
|> App.run_command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment