diff --git a/index.d.ts b/index.d.ts index c462904..2ebd800 100644 --- a/index.d.ts +++ b/index.d.ts @@ -931,6 +931,10 @@ export declare class Datagram { * The size of the buffer. */ size: number + /** + * The time between the last packet and the current packet. + */ + deltaTime: number reply(stream: BinaryStream): void } export declare class Socket { diff --git a/src/socket/datagram.rs b/src/socket/datagram.rs index 2bbaa76..3730a61 100644 --- a/src/socket/datagram.rs +++ b/src/socket/datagram.rs @@ -26,6 +26,11 @@ pub struct Datagram { */ pub size: u32, + /** + * The time between the last packet and the current packet. + */ + pub delta_time: u32, + #[napi(skip)] pub socket: UdpSocket, } @@ -35,15 +40,15 @@ impl Datagram { /** * Create a new instance of the Datagram struct. */ - pub fn new(identifier: NetworkIdentifier, buffer: Buffer, size: u32, socket: UdpSocket) -> Self { + pub fn new(identifier: NetworkIdentifier, buffer: Buffer, size: u32, socket: UdpSocket, delta_time: u32) -> Self { // Create a new BinaryStream from the buffer. let stream = BinaryStream::new(Some(buffer), None); - Self { identifier, stream, size, socket } + Self { identifier, stream, size, socket , delta_time} } #[napi] - pub fn reply(&self, stream: BinaryStream) -> Result<()> { + pub fn reply(&self, stream: &BinaryStream) -> Result<()> { match self.socket.send_to(&stream.binary, self.identifier.to_addr()) { Ok(_) => Ok(()), Err(err) => Err(err.into()) diff --git a/src/socket/socket.rs b/src/socket/socket.rs index cbb88a0..c8db3ce 100644 --- a/src/socket/socket.rs +++ b/src/socket/socket.rs @@ -74,8 +74,16 @@ impl Socket { // Create a buffer to store the incoming packet let mut buf = [0; 2048]; + let mut time = std::time::Instant::now(); + // Loop to receive packets loop { + // Calculate the delta time + let delta_time = time.elapsed().as_millis() as u32; + + // Reset the time + time = std::time::Instant::now(); + // Lock the alive mutex let alive = alive.lock().unwrap(); @@ -120,7 +128,7 @@ impl Socket { }; // Create a new Datagram instance - let datagram = Datagram::new(identifier, buffer, size as u32, socket); + let datagram = Datagram::new(identifier, buffer, size as u32, socket, delta_time); // Call the recv function recv.call(Ok(datagram), napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking); @@ -143,11 +151,11 @@ impl Socket { } #[napi] - pub fn send(&self, identifier: NetworkIdentifier, stream: BinaryStream) -> Result<()> { + pub fn send(&self, identifier: NetworkIdentifier, stream: &BinaryStream) -> Result<()> { // Lock the socket let socket = self.socket.lock().unwrap(); let addr = identifier.to_addr(); - let buf = stream.binary; + let buf = &stream.binary; // Send the packet match socket.send_to(&buf, addr) {