OCaml:Lwt表达预期为单位Lwt.t

时间:2016-09-14 16:40:54

标签: ocaml

我想为我的OUnit测试编写一个小服务器,当客户端连接套接字时,将数据发送到客户端并退出。

因为我想在我的测试中使用它,我认为我应该在一个线程中创建一个服务器并在一个线程中创建一个客户端。所以这是代码:

open Sys
open Unix
open Lwt

(* a simple server that send a message when a client  connects
 * compile with
 * ocamlfind ocamlc -o lwt_server -package lwt,lwt.unix,unix  -linkpkg -g lwt_server.ml
 * http://baturin.org/code/lwt-counter-server/
 * https://mirage.io/wiki/tutorial-lwt
 * http://aubedesheros.blogspot.fr/2011/05/ocaml-lwt-mini-tutorial.html
 *)

let host = Unix.inet_addr_loopback (* 127.0.0.1 *)
let port = 6600
let max_pending_request = 10

(* Initialize logging capabilities at INFO level *)

let () = Lwt_log.add_rule "*" Lwt_log.Info

let send_message oc =
  Lwt_io.write_line oc "test"

let accept_connection conn =
  let fd, _ = conn in
  let oc = Lwt_io.of_fd Lwt_io.Output fd in
  Lwt.on_failure (send_message oc ) (fun e -> Lwt_log.ign_error (Printexc.to_string e));
  Lwt_log.info "New connection" >>= return

let create_server sock =
  let serve () =
    Lwt_unix.accept sock >>= accept_connection
  in serve

let sock_recv sock maxlen =
  let str = Bytes.create maxlen in
  let recvlen  = recv sock str 0 maxlen [] in
  String.sub str 0 recvlen

let sock_read sock =
  let answer = sock_recv sock 512 in
    Lwt_io.write_line Lwt_io.stdout answer

let create_socket () =
  let sock = Lwt_unix.socket PF_INET SOCK_STREAM 0 in
  Lwt_unix.bind sock @@ ADDR_INET(host, port);
  Lwt_unix.listen sock max_pending_request;
  sock


let () =
  let sock = create_socket () in
    let threads = Lwt.join [create_server sock; sock_read sock] in
      Lwt_main.run threads

这是我在oder中用来编译它的命令和错误消息

ocamlfind ocamlc -o lwt_server -package lwt,lwt.unix,unix  -linkpkg -g lwt_server.ml
File "lwt_server.ml", line 53, characters 28-46:
Error: This expression has type unit -> unit Lwt.t
       but an expression was expected of type unit Lwt.t

第53行是指(没有笑话,我已经检查了两次):

        let threads = Lwt.join [create_server sock; sock_read sock] in

这是我第一次使用Lwt,我不确定它是否应该与OUnit一起使用。

1 个答案:

答案 0 :(得分:1)

问题是create_server sock返回类型unit -> unit Lwt.t的另一个函数,而不是类型错误中指示的Lwt线程(unit Lwt.t):

let create_server sock =
  let serve () =
    Lwt_unix.accept sock >>= accept_connection
  in serve (* serve is a function, not a thread *)

您可以重写此命令以返回线程而不是函数来修复此类型错误:

let create_server sock =
  Lwt_unix.accept sock >>= accept_connection

我还没有对代码进行整体测试,但这应该可以解决类型错误。