From 46ad5b3bf794e4f3d55fd7ca96b1624518160f73 Mon Sep 17 00:00:00 2001 From: maxstrb Date: Mon, 3 Nov 2025 21:23:25 +0100 Subject: [PATCH] reading websocket --- src/websoket_connection.rs | 75 ++++++++++++++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 7 deletions(-) diff --git a/src/websoket_connection.rs b/src/websoket_connection.rs index a120482..eaab754 100644 --- a/src/websoket_connection.rs +++ b/src/websoket_connection.rs @@ -27,7 +27,7 @@ struct DataBlock { mask_key: Option, - data: Box<[u8]>, + data: Vec, } struct DataFrame { @@ -42,7 +42,8 @@ enum FrameType { ConnectionClose, Ping, Pong, - Other(u8), + OtherControl(u8), + OtherNonControl(u8), } impl WebsocketConnection { @@ -50,15 +51,75 @@ impl WebsocketConnection { todo!() } - pub async fn read_next_message(&mut self) -> io::Result { + pub async fn read_next_message(&mut self) -> io::Result { + let mut data; + let frame_type; + { + let first_line = self.parse_single_block().await?; + data = first_line.data; + frame_type = first_line.message_type; + } + + Ok(DataFrame { + frame_type, + data: data.into_boxed_slice(), + }) + } + + async fn parse_single_block(&mut self) -> io::Result { let mut first_line: [u8; 2] = [0; 2]; self.stream.read_exact(&mut first_line).await?; - todo!() - } + let get_bool = |index: u8, byte: u8| -> bool { byte & (1 << index) != 0 }; - async fn parse_single_block(&self) -> io::Result { - Err(io::Error::new(io::ErrorKind::InvalidData, "uncluky")) + let is_final = get_bool(7, first_line[0]); + let extension_bit_1 = get_bool(6, first_line[0]); + let extension_bit_2 = get_bool(5, first_line[0]); + let extension_bit_3 = get_bool(4, first_line[0]); + + let message_type = match first_line[0] & 0b00001111 { + 0x0 => FrameType::Continuation, + 0x1 => FrameType::TextFrame, + 0x2 => FrameType::BinaryFrame, + 0x8 => FrameType::ConnectionClose, + 0x9 => FrameType::Ping, + 0xA => FrameType::Pong, + + non_control if (0x3..=7).contains(&non_control) => { + FrameType::OtherNonControl(non_control) + } + control => FrameType::OtherControl(control), + }; + + let mask = get_bool(7, first_line[1]); + + let length = match first_line[1] & 0b01111111 { + 126 => self.stream.read_u16().await? as u64, + 127 => self.stream.read_u64().await?, + other => other as u64, + }; + + let masking_key = if mask { + Some(self.stream.read_u32().await?) + } else { + None + }; + + let mut message_data = Vec::::with_capacity(length as usize); + + self.stream.read_exact(&mut message_data).await?; + + Ok(DataBlock { + is_final, + e1: extension_bit_1, + e2: extension_bit_2, + e3: extension_bit_3, + message_type, + is_masked: mask, + length, + mask_key: masking_key, + data: message_data, + }) } pub async fn initialize_connection(