init
This commit is contained in:
commit
e927202fc0
4 changed files with 851 additions and 0 deletions
79
src/main.rs
Normal file
79
src/main.rs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
use std::net::UdpSocket;
|
||||
use std::env;
|
||||
use std::process;
|
||||
use std::convert::TryInto;
|
||||
|
||||
/// Unpacks a 4-byte slice into two u16 values (little-endian).
|
||||
fn unpack_coordinates(buffer: &[u8]) -> Option<(u16, u16)> {
|
||||
if buffer.len() != 4 {
|
||||
return None;
|
||||
}
|
||||
// Try to convert the first 2 bytes to a u16 for x.
|
||||
let x_bytes: [u8; 2] = buffer[0..2].try_into().ok()?;
|
||||
// Try to convert the next 2 bytes to a u16 for y.
|
||||
let y_bytes: [u8; 2] = buffer[2..4].try_into().ok()?;
|
||||
|
||||
// Reconstruct the u16 values from their little-endian byte representation.
|
||||
let x = u16::from_le_bytes(x_bytes);
|
||||
let y = u16::from_le_bytes(y_bytes);
|
||||
|
||||
Some((x, y))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
|
||||
if args.len() != 3 {
|
||||
eprintln!("Usage: {} <listen_ip> <listen_port>", args[0]);
|
||||
eprintln!("Example: {} 127.0.0.1 12345", args[0]);
|
||||
process::exit(1);
|
||||
}
|
||||
|
||||
let listen_addr = &args[1];
|
||||
let listen_port = &args[2];
|
||||
let bind_address = format!("{}:{}", listen_addr, listen_port);
|
||||
|
||||
// Bind the UDP socket to the specified address and port.
|
||||
let socket = match UdpSocket::bind(&bind_address) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("Error: Could not bind to address {}: {}", bind_address, e);
|
||||
process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
println!("Listening for UDP packets on {}", bind_address);
|
||||
|
||||
// Create a buffer to hold incoming data. 4 bytes for two u16 values.
|
||||
let mut buf = [0u8; 4];
|
||||
|
||||
loop {
|
||||
// Wait for a packet to arrive.
|
||||
match socket.recv_from(&mut buf) {
|
||||
Ok((number_of_bytes, src_addr)) => {
|
||||
println!("\nReceived {} bytes from {}", number_of_bytes, src_addr);
|
||||
|
||||
// Ensure we received the correct number of bytes.
|
||||
if number_of_bytes == 4 {
|
||||
// Unpack the buffer into coordinates.
|
||||
if let Some((x, y)) = unpack_coordinates(&buf) {
|
||||
println!("Received Coordinates: X = {}, Y = {}", x, y);
|
||||
} else {
|
||||
// This case should ideally not be reached if number_of_bytes is 4.
|
||||
eprintln!("Error: Failed to unpack coordinate data.");
|
||||
}
|
||||
} else {
|
||||
eprintln!(
|
||||
"Warning: Received packet with incorrect size ({} bytes). Expected 4.",
|
||||
number_of_bytes
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error receiving data: {}", e);
|
||||
// Decide if you want to break the loop on an error.
|
||||
// For a continuous server, you might just log and continue.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue