ocaml-gopher/src/lwt_client.ml
orbifx 7b1ec728cf Introduce client & parser, switch to Dune
- Server and client now have dedicated module files
- Menu and Item have their own module files
- Wrote parsers for Menu and Item
- Switch from jbuilder to dune
- Introducing gopher client
- IPv6
2022-01-04 15:20:35 +00:00

21 lines
813 B
OCaml

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)