Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(udp-receiver): add buffer #20189

Merged
merged 1 commit into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions network-programmability/udp/udp-receiver/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions network-programmability/udp/udp-receiver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2021"

[dependencies]
prost = "0.13.3"
socket2 = "0.5.7"
tokio = { version = "1.41.0", features = ["full"] }

[dev-dependencies]
Expand Down
26 changes: 22 additions & 4 deletions network-programmability/udp/udp-receiver/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use prost::Message;
use socket2::{Socket, Domain, Type};
use std::error::Error;
use std::net::SocketAddr;
use tokio::net::UdpSocket;

pub mod iot {
Expand All @@ -10,16 +12,32 @@ use iot::Motor;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let socket = UdpSocket::bind("127.0.0.1:50537").await?;
// Create a standard UDP socket using socket2
let socket = Socket::new(Domain::IPV4, Type::DGRAM, None)?;
socket.set_reuse_address(true)?;

// Increase the buffer size to 20 MiB
socket.set_recv_buffer_size(20 * 1024 * 1024)?;

// Bind the socket to the address
let addr: SocketAddr = "127.0.0.1:50537".parse()?;
socket.bind(&addr.into())?;

// Convert socket2::Socket into tokio::net::UdpSocket
let socket = UdpSocket::from_std(socket.into())?;
println!("Listening on 127.0.0.1:50537");

let mut buffer = vec![0u8; 1024]; // Buffer to hold received data
let mut message_count = 0; // Counter for received messages

loop {
let (amt, src) = socket.recv_from(&mut buffer).await?;
let (amt, _src) = socket.recv_from(&mut buffer).await?;
match Motor::decode(&buffer[..amt]) {
Ok(motor) => {
println!("Received from {}: {:?}", src, motor);
Ok(_motor) => {
message_count += 1;
if message_count % 10000 == 0 {
println!("Total messages received: {}", message_count);
}
}
Err(e) => {
eprintln!("Failed to decode protobuf message: {}", e);
Expand Down
Loading