this repo has no description
1open Swim.Types
2
3external env_cast : 'a -> 'b = "%identity"
4
5let hex_of_cstruct cs =
6 let len = Cstruct.length cs in
7 let buf = Buffer.create (len * 2) in
8 for i = 0 to len - 1 do
9 Buffer.add_string buf (Printf.sprintf "%02x" (Cstruct.get_uint8 cs i))
10 done;
11 Buffer.contents buf
12
13let () =
14 Eio_main.run @@ fun env ->
15 let env = env_cast env in
16 Eio.Switch.run @@ fun sw ->
17 let net = env#net in
18 let sock =
19 Swim.Transport.create_udp_socket net ~sw ~addr:"\127\000\000\001" ~port:7947
20 in
21
22 Printf.printf "Bound to 127.0.0.1:7947\n%!";
23
24 (* Create and send a ping to Go memberlist *)
25 let self =
26 make_node_info
27 ~id:(node_id_of_string "ocaml-node")
28 ~addr:(`Udp (Eio.Net.Ipaddr.of_raw "\127\000\000\001", 7947))
29 ~meta:""
30 in
31 let target_id = node_id_of_string "go-node" in
32 let ping = Ping { seq = 1; target = target_id; sender = self } in
33
34 let packet = { cluster = ""; primary = ping; piggyback = [] } in
35 let send_buf = Cstruct.create 1500 in
36 match Swim.Codec.encode_packet packet ~buf:send_buf with
37 | Error _ -> Printf.eprintf "Encode failed\n"
38 | Ok len ->
39 let encoded = Cstruct.sub send_buf 0 len in
40 Printf.printf "Sending ping (%d bytes): %s\n%!" len
41 (hex_of_cstruct encoded);
42
43 let dst = `Udp (Eio.Net.Ipaddr.of_raw "\127\000\000\001", 7946) in
44 Eio.Net.send sock ~dst [ encoded ];
45 Printf.printf "Sent! Waiting for ack...\n%!";
46
47 (* Wait for response *)
48 let recv_buf = Cstruct.create 1500 in
49 for i = 1 to 5 do
50 Printf.printf "Waiting for packet %d (with 2s timeout)...\n%!" i;
51 Eio.Fiber.fork ~sw (fun () ->
52 let src, n = Eio.Net.recv sock recv_buf in
53 let received = Cstruct.sub recv_buf 0 n in
54 Printf.printf "Received %d bytes from %s\n%!" n
55 (match src with
56 | `Udp (ip, port) ->
57 Printf.sprintf "%s:%d"
58 (Fmt.to_to_string Eio.Net.Ipaddr.pp ip)
59 port
60 | _ -> "unknown");
61 Printf.printf "Hex: %s\n%!" (hex_of_cstruct received);
62 Printf.printf "First byte (msg type): %d\n%!"
63 (Cstruct.get_uint8 received 0));
64 Eio.Time.sleep env#clock 2.0
65 done