2014-09-20 82 views
3

我不確定如何完全使用OCaml Websocket庫。我希望有人能用一個簡單的例子來幫助我。我正試圖在websocket.org上測試這個庫。我只是想發送一條消息,然後打印迴應。我很困惑如何使用/訪問由ws_conn返回的功能。我認爲我可以像let push,print = ws_conn inlet push,print = Websocket.open_connection ~tls:false ws_addr in這樣做,但這似乎不正確。這是我到目前爲止。OCaml Websocket示例

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

回答

5

感謝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 
+0

看起來不錯。很高興我能幫上忙。 :) – nlucaroni 2014-09-22 22:30:03

+0

此API不再工作,Websocket庫不再具有「open_connection」功能。 – 2017-12-28 07:17:50

3

open_connection函數返回,

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

'a Lwt.t是返回對打印數據流,併爲您的使用推功能的線程。您可以單向使用'a Lwt.t,並且可以找到一個簡單的教程http://ocsigen.org/lwt/manual/