OCaml Websocket example
I'm not sure how to fully use the OCaml Websocket library. I was hoping someone could help me with a simple example. I am trying to test a library at websocket.org. I am just trying to send a message and then print the response. I am confused about how to use / access the functions returned ws_conn
. I thought I could do something like let push,print = ws_conn in
or let push,print = Websocket.open_connection ~tls:false ws_addr in
, but that doesn't seem right. Here's what I have so far.
#require "websocket";;
(* Set up the websocket uri address *)
let ws_addr = Uri.of_string "ws://echo.websocket.org"
(* Set up the websocket connection *)
let ws_conn = Websocket.open_connection ~tls:false ws_addr
(* Set up a frame *)
let ws_frame = Websocket.Frame.of_string "Rock it with HTML5 WebSocket"
(* Function to handle replies *)
let with_reply s =
match s with
| Some x ->
let line = Websocket.Frame.content x in
print_string line
| None ->
print_string "Error Recieved no reply ..."
source to share
Thanks nlucaroni, after further reading, I created a specific example as an answer to my question.
#require "websocket";;
#require "lwt";;
#require "lwt.syntax";;
(* Set up the uri address *)
let ws_addr = Uri.of_string "ws://echo.websocket.org"
(* Set up the websocket connection *)
let ws_conn = Websocket.open_connection ~tls:false ws_addr
(* Function to print a frame reply *)
let f (x : Websocket.Frame.t) =
let s = Websocket.Frame.content x in
print_string s;
Lwt.return ()
(* push a string *)
let push_msg =
ws_conn
>>= fun (_, ws_pushfun) ->
let ws_frame = Websocket.Frame.of_string msg in
ws_pushfun (Some ws_frame);
Lwt.return ()
(* print stream element *)
let print_element () =
ws_conn
>>= fun (ws_stream, _) ->
Lwt_stream.next ws_stream
>>= f
(* push string and print response *)
let push_print msg =
ws_conn
>>= fun(ws_stream, ws_pushfun) ->
let ws_frame = Websocket.Frame.of_string msg in
ws_pushfun (Some ws_frame);
Lwt_stream.next ws_stream >>= f
source to share
The function open_connection
returns,
(Frame.t Lwt_stream.t * (Frame.t option -> unit)) Lwt.t
'a Lwt.t
is a stream that returns a print stream pair and a push function for your use. You are using a 'a Lwt.t
monadic way and a simple tutorial can be found at http://ocsigen.org/lwt/manual/ .
source to share