gpt4 book ai didi

websocket - OCaml Websocket 示例

转载 作者:行者123 更新时间:2023-12-04 17:18:57 26 4
gpt4 key购买 nike

我不确定如何充分使用 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

关于websocket - OCaml Websocket 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com