OCaml Websocket示例

时间:2014-09-20 20:35:08

标签: websocket ocaml

我不确定如何完全使用OCaml Websocket库。我希望有人可以通过一个简单的例子来帮助我。我试图在websocket.org上测试库。我只是想发送一条消息,然后打印响应。我对如何使用/访问ws_conn返回的函数感到困惑。我认为我可以做let push,print = ws_conn inlet push,print = Websocket.open_connection ~tls:false ws_addr in之类的事情,但这似乎不正确。这是我到目前为止所拥有的。

    #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 ..."

2 个答案:

答案 0 :(得分:6)

感谢nlucaroni,在进一步阅读之后,我已经创建了一个具体的例子来回答我的问题。

    #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

答案 1 :(得分:4)

open_connection函数返回,

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

'a Lwt.t是一个线程,它返回一对打印流和一个推送功能供您使用。您以monadic方式使用'a Lwt.t,可以找到一个简单的教程http://ocsigen.org/lwt/manual/