Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml Websocket example

I am not sure how to fully use the OCaml Websocket library. I was hoping that somebody could help me out with a simple example. I am trying to test the library out on websocket.org. I am just trying to send a message and then print the response. I'm confused as to how to use/access the functions returned by ws_conn. I thought that 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 does not seem to be correct. Here is 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 ..."
like image 872
Thomas Avatar asked Sep 20 '14 20:09

Thomas


2 Answers

Thanks nlucaroni, after further reading I have created a concrete 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
like image 52
Thomas Avatar answered Oct 30 '22 08:10

Thomas


The open_connection function returns,

(Frame.t Lwt_stream.t * (Frame.t option -> unit)) Lwt.t

the 'a Lwt.t is a thread that returns the pair of a print stream and a push function for your use. You use the 'a Lwt.t in a monadic way, and a simple tutorial can be found http://ocsigen.org/lwt/manual/ .

like image 21
nlucaroni Avatar answered Oct 30 '22 06:10

nlucaroni