Utf 8 OCaml websocket“;无效的UTF8数据“;

Utf 8 OCaml websocket“;无效的UTF8数据“;,utf-8,websocket,ocaml,ocsigen,ocaml-lwt,Utf 8,Websocket,Ocaml,Ocsigen,Ocaml Lwt,我正在尝试使用Lwt构建一个循环,将一个帧推送到Websocket,等待响应,将其打印到屏幕上,等待60秒,然后再次重复该过程。我已经能够得到一些编译的东西,但我还没有完全正确。第一次通过循环时,一切正常,然后每次之后我都会收到错误消息“无效UTF8数据”。我的Lwt循环或对Websocket协议的理解一定有问题。我的代码: #require "websocket";; #require "lwt";; #require "lwt.syntax";; open Lwt (* Set up t

我正在尝试使用Lwt构建一个循环,将一个帧推送到Websocket,等待响应,将其打印到屏幕上,等待60秒,然后再次重复该过程。我已经能够得到一些编译的东西,但我还没有完全正确。第一次通过循环时,一切正常,然后每次之后我都会收到错误消息“无效UTF8数据”。我的Lwt循环或对Websocket协议的理解一定有问题。我的代码:

#require "websocket";;
#require "lwt";;
#require "lwt.syntax";;

open Lwt

(* Set up the websocket uri address *)
let ws_addr = Uri.of_string "websocket_address"

(* Set up the websocket connection *)
let ws_conn = Websocket.open_connection ws_addr

(* Set up a frame *)
let ws_frame = Websocket.Frame.of_string "json_string_to_server"

(* push function *)
let push frame () =
  ws_conn 
  >>= fun (_, ws_pushfun) ->
    ws_pushfun (Some frame);
    Lwt.return ()

(* get stream element and print to screen *)
let get_element () = 
  let print_reply (x : Websocket.Frame.t) = 
    let s = Websocket.Frame.content x in
    Lwt_io.print s; Lwt_io.flush Lwt_io.stdout;
  in
  ws_conn
  >>= fun(ws_stream, _) ->
      Lwt_stream.next ws_stream
      >>= print_reply 

let rec main () =
  Lwt_unix.sleep 60.0
  >>= (push ws_frame)
  >>= get_element
  >>= main

Lwt_main.run(main ())

我不确定你的代码有什么特别不正确的地方。它甚至不能在我的系统上编译。看起来你是在顶层进行实验,创造了一些奇怪的环境。我已经用一种更简洁的方式重写了你的代码。首先,我向函数传递一个连接,这样函数的功能就更清晰了。同样,反复等待同一个线程也不是一个好主意。事情不是这样做的,而是Lwt

open Lwt

(* Set up the websocket uri address *)
let ws_addr = Uri.of_string "websocket_address"

(* Set up a frame *)
let ws_frame = Websocket.Frame.of_string "json_string_to_server"

(* push function *)
let push (_,push) frame  =
  push (Some frame);
  return_unit


(* get stream element and print to screen *)
let get_element (stream,_) =
  let print_reply (x : Websocket.Frame.t) =
    let s = Websocket.Frame.content x in
    Lwt_io.printlf "%s%!" s in
    Lwt_stream.next stream
    >>= print_reply

let rec main conn : unit t =
  Lwt_unix.sleep 60.0
  >>= fun () -> push conn ws_frame
  >>= fun () -> get_element conn
  >>= fun () -> main conn

let () = Lwt_main.run (
    Websocket.open_connection ws_addr >>= main)

我试过你的代码,遇到了同样的问题。我第一次得到一个结果,然后在第一次运行main之后,我收到“Invalid UTF8 data”错误。我已经在多个WebSocket上尝试了我的版本和你的版本,以确保它不是特定服务器的问题。(注意:我必须删除代码中的类型签名才能编译。)好的,看来问题不在代码中。也许实施还不够充分。我建议您使用websocket库中的示例程序进行实验。有服务器和客户端实现,您可以启动服务器并检查它是否可以与客户端通信。接下来,您可以使用他们的客户机与您的服务器进行对话,等等。