changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / rust/lib/sxp/examples/udp.rs

changeset 698: 96958d3eb5b0
parent: 3d78bed56188
author: Richard Westhaver <ellis@rwest.io>
date: Fri, 04 Oct 2024 22:04:59 -0400
permissions: -rw-r--r--
description: fixes
1 //! udp client example
2 
3 //! to use this example - start one instance, then in a separate
4 //! terminal start another which connects to the first:
5 
6 //! > cargo run --example udp 9980
7 
8 //! > cargo run --example udp 9981 9980
9 
10 //! PS - you can change the formatter by specifying one on the command
11 //! line. It affects both read and write streams.
12 
13 //! > cargo run --example udp 9980 binary
14 use serde_derive::{Deserialize, Serialize};
15 use std::{
16  net::{SocketAddr, UdpSocket},
17  time::Duration,
18 };
19 #[derive(Serialize, Deserialize)]
20 struct Packet {
21  id: usize,
22  key: String,
23  payload: Vec<f64>,
24 }
25 
26 impl Packet {
27  fn new() -> Self {
28  Packet {
29  id: 0,
30  key: String::new(),
31  payload: vec![],
32  }
33  }
34  fn next(&mut self) -> Vec<u8> {
35  self.id += 1;
36  self.payload = rand::random::<[f64; 32]>().to_vec();
37  sxp::to_vec(&self).unwrap()
38  }
39 }
40 
41 fn main() {
42  let mut args = std::env::args().skip(1);
43  let addr = SocketAddr::new(
44  "127.0.0.1".parse().unwrap(),
45  args.next().unwrap().parse::<u16>().unwrap(),
46  );
47  let socket = UdpSocket::bind(addr).expect("failed to bind socket");
48  socket
49  .set_read_timeout(Some(Duration::from_millis(500)))
50  .unwrap();
51  let mut peer = None;
52  let mut rx = [0u8; 1024];
53  let mut tx = Packet::new();
54  for x in args {
55  if let Ok(x) = x.parse::<u16>() {
56  peer = Some(SocketAddr::new("127.0.0.1".parse().unwrap(), x));
57  socket.connect(peer.unwrap()).unwrap();
58  } else {
59  match x.as_str() {
60  "default" => (),
61  "binary" => (),
62  "pretty" => (),
63  _ => eprintln!("invalid formatter"),
64  }
65  }
66  }
67 
68  loop {
69  if let Ok(_) = socket.recv(&mut rx) {
70  println!("{}", String::from_utf8_lossy(&rx).trim_end_matches('\0'));
71  rx = rx.map(|_| 0);
72  } else if let Some(p) = peer {
73  std::thread::sleep(Duration::from_millis(500));
74  tx.key = String::from_utf8_lossy(rand::random::<[u8; 32]>().as_slice())
75  .to_string();
76  // send a struct
77  let bytes = socket.send(&mut tx.next()).unwrap();
78  println!("(:sent {bytes} :to {p})");
79  }
80  }
81 }