Skip to main content

response_sample/
response-sample.rs

1#![allow(clippy::expect_used, reason = "helps to reduce verbosity")]
2
3use rsomeip_bytes::{BytesMut, Serialize};
4use rsomeip_proto::{Endpoint, Interface, MessageType};
5use std::net::UdpSocket;
6
7mod common;
8use common::{SAMPLE_METHOD_ID, SAMPLE_SERVICE_ID, stub_address};
9
10// A SOME/IP message.
11type Message = rsomeip_proto::Message<Vec<u8>>;
12
13fn main() {
14    // Bind an UDP socket.
15    let socket = UdpSocket::bind(stub_address()).expect("should bind the socket");
16
17    // Create the SOME/IP endpoint.
18    let endpoint = Endpoint::new().with_interface(
19        SAMPLE_SERVICE_ID,
20        Interface::default()
21            .with_method(SAMPLE_METHOD_ID)
22            .into_stub(),
23    );
24
25    // Process requests and send back responses.
26    send_responses(&socket, &endpoint);
27}
28
29fn send_responses(socket: &UdpSocket, endpoint: &Endpoint) {
30    // Continuously process requests from service consumers.
31    loop {
32        // Wait for a request.
33        let mut buffer = BytesMut::zeroed(64);
34        let (size, remote_address) = socket
35            .recv_from(&mut buffer[..])
36            .expect("should receive the data");
37
38        // Process the request.
39        let request: Message = endpoint
40            .poll(&mut buffer.split_to(size).freeze())
41            .expect("should process the request");
42        println!("< {request} {:02x?}", request.body);
43
44        // Create a response.
45        let response = request.clone().with_message_type(MessageType::Response);
46        println!("> {response} {:02x?}", response.body);
47
48        // Process the response into bytes.
49        let mut buffer = BytesMut::with_capacity(request.size_hint());
50        endpoint
51            .process(response, &mut buffer)
52            .expect("should process the response");
53
54        // Send the data through the socket.
55        socket
56            .send_to(&buffer.freeze(), remote_address)
57            .expect("should send the data.");
58    }
59}