From 0b484df40c356cf4fe87f3d3a20eadf59eef42c9 Mon Sep 17 00:00:00 2001 From: mat Date: Mon, 6 Dec 2021 19:59:20 +0000 Subject: implement new packet implementation --- minecraft-protocol/src/connection.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) (limited to 'minecraft-protocol/src/connection.rs') 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 = 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(); + } } -- cgit v1.2.3