open Swim.Types external env_cast : 'a -> 'b = "%identity" let hex_of_cstruct cs = let len = Cstruct.length cs in let buf = Buffer.create (len * 2) in for i = 0 to len - 1 do Buffer.add_string buf (Printf.sprintf "%02x" (Cstruct.get_uint8 cs i)) done; Buffer.contents buf let () = Eio_main.run @@ fun env -> let env = env_cast env in Eio.Switch.run @@ fun sw -> let net = env#net in let sock = Swim.Transport.create_udp_socket net ~sw ~addr:"\127\000\000\001" ~port:7947 in Printf.printf "Listening on 127.0.0.1:7947 for UDP packets...\n%!"; let buf = Cstruct.create 1500 in for i = 1 to 10 do Printf.printf "Waiting for packet %d...\n%!" i; let src, n = Eio.Net.recv sock buf in let received = Cstruct.sub buf 0 n in Printf.printf "Received %d bytes from %s\n%!" n (match src with | `Udp (ip, port) -> Printf.sprintf "%s:%d" (Fmt.to_to_string Eio.Net.Ipaddr.pp ip) port | _ -> "unknown"); Printf.printf "Hex: %s\n%!" (hex_of_cstruct received); Printf.printf "First byte (msg type): %d\n%!" (Cstruct.get_uint8 received 0); (* Try to decode *) match Swim.Codec.decode_packet received with | Ok packet -> Printf.printf "Decoded! Cluster: %s\n%!" packet.cluster | Error e -> Printf.printf "Decode error: %s\n%!" (decode_error_to_string e) done