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 |
3 //! to use this example - start one instance, then in a separate 4 //! terminal start another which connects to the first: 6 //! > cargo run --example udp 9980 8 //! > cargo run --example udp 9981 9980 10 //! PS - you can change the formatter by specifying one on the command 11 //! line. It affects both read and write streams. 13 //! > cargo run --example udp 9980 binary 14 use serde_derive::{Deserialize, Serialize}; 16 net::{SocketAddr, UdpSocket}, 19 #[derive(Serialize, Deserialize)] 34 fn next(&mut self) -> Vec<u8> { 36 self.payload = rand::random::<[f64; 32]>().to_vec(); 37 sxp::to_vec(&self).unwrap() 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(), 47 let socket = UdpSocket::bind(addr).expect("failed to bind socket"); 49 .set_read_timeout(Some(Duration::from_millis(500))) 52 let mut rx = [0u8; 1024]; 53 let mut tx = Packet::new(); 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(); 63 _ => eprintln!("invalid formatter"), 69 if let Ok(_) = socket.recv(&mut rx) { 70 println!("{}", String::from_utf8_lossy(&rx).trim_end_matches('\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()) 77 let bytes = socket.send(&mut tx.next()).unwrap(); 78 println!("(:sent {bytes} :to {p})");