I wanted to try the Lwt_unix
module for a simple client that reads data in a socket until there is nothing to read. Some told me that Lwt
create non blocking sockets but with my code, it is still blocking:
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)
If I try this example with in a term:
echo "totoche" | netcat -l 127.0.0.1 -p 6600
then the result is :
./lwt_socket_client
_read
8
_read
Which block until I hit Ctrl+c.
I have tried both with :
Lwt_unix.set_blocking sock false;
and
Lwt_unix.set_blocking sock true;
and of course without this line, but it is still blocking. What am I doing wrong?
For more informations, one of my previous question : OCaml non-blocking client socket