aboutsummaryrefslogtreecommitdiff
path: root/minecraft-protocol/src/connection.rs
diff options
context:
space:
mode:
Diffstat (limited to 'minecraft-protocol/src/connection.rs')
-rw-r--r--minecraft-protocol/src/connection.rs33
1 files changed, 31 insertions, 2 deletions
diff --git a/minecraft-protocol/src/connection.rs b/minecraft-protocol/src/connection.rs
index 4fa1cde7..79058a75 100644
--- a/minecraft-protocol/src/connection.rs
+++ b/minecraft-protocol/src/connection.rs
@@ -1,6 +1,9 @@
-use crate::ServerIpAddress;
+use crate::{friendly_byte_buf::FriendlyByteBuf, packets::Packet, ServerIpAddress};
use bytes::BytesMut;
-use tokio::{io::BufWriter, net::TcpStream};
+use tokio::{
+ io::{AsyncWriteExt, BufWriter},
+ net::TcpStream,
+};
pub enum PacketFlow {
ClientToServer,
@@ -35,4 +38,30 @@ impl Connection {
buffer: BytesMut::with_capacity(4 * 1024 * 1024),
})
}
+
+ /// Write a packet to the server
+ pub async fn send_packet(&mut self, packet: &dyn Packet) {
+ // packet structure:
+ // length + id + data
+
+ // Is this efficient? I have no idea, probably not.
+ // getting rid of the FriendlyByteBuffer struct might help
+
+ // write the packet id
+ let mut id_and_data_buf = vec![packet.get_id()];
+
+ // write the packet data
+ let mut id_and_data_friendly_buf = FriendlyByteBuf::new(&mut id_and_data_buf);
+ packet.write(&mut id_and_data_friendly_buf);
+
+ // add the packet length to the beginning
+ let mut complete_buf: Vec<u8> = Vec::new();
+ let mut complete_friendly_buf = FriendlyByteBuf::new(&mut complete_buf);
+ complete_friendly_buf.write_varint(id_and_data_buf.len() as u32);
+ complete_buf.append(&mut id_and_data_buf);
+
+ // finally, write and flush to the stream
+ self.stream.write_all(&complete_buf).await.unwrap();
+ self.stream.flush().await.unwrap();
+ }
}