1 object Sys 2 let inaddr_any : u32 = 0 3 4 def init_sockets "kd_init_sockets" 5 let make_reusable "kd_make_reusable" (fd : int) 6 let accept (fd : int 7 addr : Ptr<Address> 8 addr_len : Ptr<usize>) : int 9 let bind (fd : int 10 addr : Ptr<Address> 11 len : usize) : int 12 let listen (fd : int) (n : int) : int 13 14 type TcpListener = 15 let fd : int 16 let address : Address 17 let address_size = sizeof Address as usize 18 19 def try_next : Option<TcpStream> = 20 let x = accept fd address@ptr address_size@ptr 21 22 if x < 0 23 then None 24 else TcpStream x |> Some 25 26 def discard = 27 close fd |> ignore 28 29 object TcpListener = 30 def bind (port : u16) = 31 let fd = create_socket 32 let is_blocking @param = false 33 34 if fd < 0 then 35 fail "cannot create socket" 36 37 if not is_blocking then 38 set_nonblocking fd 39 40 make_reusable fd 41 42 let address = Address 43 family = Sys.af_inet 44 port = htons port 45 ip_address = Sys.inaddr_any 46 47 let address_length = sizeof Address as usize 48 let bind_result = bind fd address@ptr address_length 49 50 if bind_result < 0 then 51 fail "bind failed" 52 53 let listen_result = listen fd 3 54 if listen_result < 0 then 55 fail "listen" 56 57 TcpListener =fd =address 58