我不知道如何完全使用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 ..."
感谢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
open_connection
函数返回
(Frame.t Lwt_stream.t * (Frame.t option -> unit)) Lwt.t
CCD_ 5是一个返回打印流和推送函数对供您使用的线程。以一元的方式使用'a Lwt.t
,可以找到一个简单的教程http://ocsigen.org/lwt/manual/。