ocaml-gopher/src/lwt_client.ml

22 lines
813 B
OCaml
Raw Normal View History

open Lwt.Infix
let session socket path () =
let rec recv_all reply_bytes () =
let recv_bytes = Bytes.create 4096 in
Lwt_unix.recv socket recv_bytes 0 (Bytes.length recv_bytes) []
>>= function
| 0 -> Lwt.return (Bytes.to_string reply_bytes)
| _ -> recv_all (Bytes.cat reply_bytes recv_bytes) ()
in
let path_bytes = Bytes.of_string path in
Lwt_unix.send socket path_bytes 0 (Bytes.length path_bytes) []
>>= function
| -1 | 0 -> Lwt_result.fail "Couldn't send"
| _ -> Lwt_result.ok (recv_all (Bytes.create 0) ())
let gopher ?(port=70) host path =
let socket = Lwt_unix.(socket PF_INET SOCK_STREAM 0) in
let host = Unix.inet_addr_of_string host in
let connection = Lwt_unix.connect socket Unix.(ADDR_INET (host, port)) in
Lwt_main.run (connection >>= session socket path)