this repo has no description
at main 2.2 kB view raw
1open Types 2 3let create_udp_socket (net : _ Eio.Net.t) ~sw ~addr ~port : 4 _ Eio.Net.datagram_socket_ty Eio.Resource.t = 5 let bind_addr = 6 match Eio.Net.Ipaddr.of_raw addr with ip -> `Udp (ip, port) 7 in 8 Eio.Net.datagram_socket ~sw net bind_addr 9 10let send_udp sock dst buf = Eio.Net.send sock ~dst [ buf ] 11 12let recv_udp sock buf = 13 let dst, n = Eio.Net.recv sock buf in 14 (n, dst) 15 16let create_tcp_listener (net : _ Eio.Net.t) ~sw ~addr ~port ~backlog = 17 let bind_addr = 18 match Eio.Net.Ipaddr.of_raw addr with ip -> `Tcp (ip, port) 19 in 20 Eio.Net.listen ~sw ~backlog net bind_addr 21 22let connect_tcp (net : _ Eio.Net.t) ~sw ~addr ~timeout ~clock = 23 try 24 Ok 25 (Eio.Time.with_timeout_exn clock timeout (fun () -> 26 Eio.Net.connect ~sw net addr)) 27 with 28 | Eio.Time.Timeout -> Error Timeout 29 | Eio.Io (Eio.Net.E (Connection_failure _), _) -> Error Node_unreachable 30 | Eio.Io (Eio.Net.E (Connection_reset _), _) -> Error Connection_reset 31 32let send_tcp sock buf = 33 try 34 Eio.Flow.write sock [ buf ]; 35 Ok () 36 with 37 | Eio.Io (Eio.Net.E (Connection_reset _), _) -> Error Connection_reset 38 | End_of_file -> Error Connection_reset 39 40let recv_tcp sock buf = 41 try 42 let n = Eio.Flow.single_read sock buf in 43 Ok n 44 with 45 | Eio.Io (Eio.Net.E (Connection_reset _), _) -> Error Connection_reset 46 | End_of_file -> Error Connection_reset 47 48let parse_addr_port s = 49 match String.rindex_opt s ':' with 50 | None -> Error `Invalid_addr 51 | Some idx -> ( 52 let host = String.sub s 0 idx in 53 let port_str = String.sub s (idx + 1) (String.length s - idx - 1) in 54 match int_of_string_opt port_str with 55 | None -> Error `Invalid_addr 56 | Some port -> 57 if port < 0 || port > 65535 then Error `Invalid_addr 58 else Ok (host, port)) 59 60let parse_udp_addr s = 61 match parse_addr_port s with 62 | Error e -> Error e 63 | Ok (host, port) -> ( 64 try 65 let ip = Eio.Net.Ipaddr.of_raw host in 66 Ok (`Udp (ip, port)) 67 with _ -> Error `Invalid_addr) 68 69let parse_tcp_addr s = 70 match parse_addr_port s with 71 | Error e -> Error e 72 | Ok (host, port) -> ( 73 try 74 let ip = Eio.Net.Ipaddr.of_raw host in 75 Ok (`Tcp (ip, port)) 76 with _ -> Error `Invalid_addr)