我想为Lwt_unix模块尝试一个简单的客户端,它可以读取套接字中的数据,直到没有任何内容可读。有人告诉我,Lwt创建了非阻塞套接字,但是使用我的代码,它仍然阻塞:
open Lwt
open Unix
(* ocamlfind ocamlc -o lwt_socket_client -package lwt,lwt.unix,unix -linkpkg -g lwt_socket_client.ml *)
let host = Unix.inet_addr_loopback
let port = 6600
let create_socket () =
let sock = Lwt_unix.socket PF_INET SOCK_STREAM 0 in
Lwt_unix.set_blocking sock false;
sock
let s_read sock maxlen =
let str = Bytes.create maxlen in
let rec _read sock acc =
Lwt.ignore_result(Lwt_io.write_line Lwt_io.stdout "_read");
Lwt_unix.read sock str 0 maxlen >>= fun recvlen ->
Lwt.ignore_result(Lwt_io.write_line Lwt_io.stdout (string_of_int recvlen));
if recvlen = 0 then Lwt.return (acc)
else _read sock (acc ^ (String.sub str 0 recvlen))
in _read sock ""
let socket_read sock =
Lwt.ignore_result(Lwt_unix.connect sock @@ ADDR_INET(host, port));
s_read sock 1024 >>= fun answer ->
Lwt_io.write_line Lwt_io.stdout answer
let () =
let sock = create_socket () in
Lwt_main.run (socket_read sock)如果我用一个术语尝试这个例子:
echo "totoche" | netcat -l 127.0.0.1 -p 6600那么结果是:
./lwt_socket_client
_read
8
_read直到我点击Ctrl kbd> + c kbd>时才阻止。
我曾尝试过:
Lwt_unix.set_blocking sock false;和
Lwt_unix.set_blocking sock true;当然没有这条线,但它仍然阻塞。我究竟做错了什么?
欲了解更多信息,我之前的一个问题:
OCaml non-blocking client socket