blob: bf9fd0aaf61a0fdfcc0af63c880fa9d22e6e7388 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
use tokio::{io::AsyncWriteExt, net::TcpStream};
use crate::{mc_buf::Writable, packets::ProtocolPacket};
pub async fn write_packet(packet: impl ProtocolPacket, stream: &mut TcpStream) {
// TODO: implement compression
// packet structure:
// length (varint) + id (varint) + data
// write the packet id
let mut id_and_data_buf = vec![];
id_and_data_buf
.write_varint(packet.id() as i32)
.expect("Writing packet id failed");
packet.write(&mut id_and_data_buf);
// write the packet data
// make a new buffer that has the length at the beginning
// and id+data at the end
let mut complete_buf: Vec<u8> = Vec::new();
complete_buf
.write_varint(id_and_data_buf.len() as i32)
.expect("Writing packet length failed");
complete_buf.append(&mut id_and_data_buf);
// finally, write and flush to the stream
stream.write_all(&complete_buf).await.unwrap();
stream.flush().await.unwrap();
}
|