我不确定如何充分使用OCaml Websocket库.我希望有人可以通过一个简单的例子来帮助我.我试图在websocket.org上测试库.我只是想发送一条消息,然后打印响应.我很困惑如何使用/访问返回的函数ws_conn.我以为我可以做类似的事情let push,print = ws_conn in,let 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 ..."
Run Code Online (Sandbox Code Playgroud)
感谢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
Run Code Online (Sandbox Code Playgroud)
该open_connection函数返回,
(Frame.t Lwt_stream.t * (Frame.t option -> unit)) Lwt.t
Run Code Online (Sandbox Code Playgroud)
该'a Lwt.t线程返回一对打印流和推送函数供您使用。您可以'a Lwt.t以单子的方式使用它,可以在http://ocsigen.org/lwt/manual/找到一个简单的教程。
| 归档时间: |
|
| 查看次数: |
1704 次 |
| 最近记录: |