udp_client/
udp_client.rs

1//! UDP client example.
2//!
3//! This example demonstrates a SOME/IP UDP client that sends
4//! requests and receives responses.
5//!
6//! Run the server first: cargo run --example udp_server
7//! Then run: cargo run --example udp_client
8
9use someip_rs::transport::UdpClient;
10use someip_rs::{ClientId, MethodId, ServiceId, SomeIpMessage};
11use std::time::Duration;
12
13const SERVICE_ID: u16 = 0x4321;
14const METHOD_REVERSE: u16 = 0x0001;
15const SERVER_ADDR: &str = "127.0.0.1:30491";
16
17fn main() -> Result<(), Box<dyn std::error::Error>> {
18    println!("Creating SOME/IP UDP client...");
19
20    let mut client = UdpClient::new()?;
21    client.set_client_id(ClientId(0x0200));
22    client.set_read_timeout(Some(Duration::from_secs(5)))?;
23
24    println!("Client bound to {}", client.local_addr()?);
25
26    // Example 1: Request with call_to (specify address per-request)
27    println!("\n--- Example 1: Request/Response ---");
28    let request = SomeIpMessage::request(ServiceId(SERVICE_ID), MethodId(METHOD_REVERSE))
29        .payload(b"Hello UDP!".as_slice())
30        .build();
31
32    println!(
33        "Sending: {:?}",
34        String::from_utf8_lossy(&request.payload)
35    );
36
37    let response = client.call_to(SERVER_ADDR, request)?;
38    println!(
39        "Received: {:?} (reversed)",
40        String::from_utf8_lossy(&response.payload)
41    );
42
43    // Example 2: Connect and use call()
44    println!("\n--- Example 2: Connected Mode ---");
45    client.connect(SERVER_ADDR)?;
46    println!("Connected to {SERVER_ADDR}");
47
48    for word in ["Rust", "SOME/IP", "Automotive"] {
49        let request = SomeIpMessage::request(ServiceId(SERVICE_ID), MethodId(METHOD_REVERSE))
50            .payload(word.as_bytes().to_vec())
51            .build();
52
53        let response = client.call(request)?;
54        println!(
55            "{} -> {}",
56            word,
57            String::from_utf8_lossy(&response.payload)
58        );
59    }
60
61    // Example 3: Send notification (fire-and-forget)
62    println!("\n--- Example 3: Notification ---");
63    let notification = SomeIpMessage::notification(ServiceId(SERVICE_ID), MethodId(0x8001))
64        .payload(b"Event occurred!".as_slice())
65        .build();
66
67    client.send(notification)?;
68    println!("Notification sent!");
69
70    println!("\nDone!");
71    Ok(())
72}