Skip to content

Instantly share code, notes, and snippets.

@et4te
Created January 9, 2019 15:54
Show Gist options
  • Save et4te/9556d5a81afe3b20bf351637ee517757 to your computer and use it in GitHub Desktop.
Save et4te/9556d5a81afe3b20bf351637ee517757 to your computer and use it in GitHub Desktop.
Reads by forcing non-blocking on the fd and doesn't explicitly retry on the errors
open Lwt
open Lwt_unix
let read fd =
let maxlen = 1024 in
let buf = Bytes.create maxlen in
Lwt.catch
(fun _ ->
Lwt_log.info "reading" >>= fun () ->
let len = Unix.read (Lwt_unix.unix_file_descr fd) buf 0 maxlen in
if len = 0 then
Lwt_log.info "len = 0"
else
Lwt_log.info "got some bytes")
(fun err ->
match err with
| Unix.Unix_error (EAGAIN,_,_) ->
Lwt_log.info (Printf.sprintf "error = EAGAIN")
| _ ->
Lwt_log.info (Printf.sprintf "error = _"))
let connect fd =
ignore(Lwt_unix.connect fd @@ ADDR_INET(Unix.inet_addr_of_string "172.217.195.113", 80));
read fd >>= fun _ ->
Lwt.return 0
let () =
Lwt_log.default :=
Lwt_log.channel
~template:"$(date).$(milliseconds) [$(level)] $(message)"
~close_mode:`Keep
~channel:Lwt_io.stdout
();
Lwt_log.add_rule "*" Lwt_log.Info;
Lwt_main.run begin
let fd = Lwt_unix.socket PF_INET SOCK_STREAM 0 in
Pervasives.exit (Lwt_main.run (connect fd))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment