websocket and data:

This commit is contained in:
maxstrb 2025-11-04 22:41:01 +01:00
parent 964c90d2f2
commit 1893eb0599
5 changed files with 65 additions and 50 deletions

View file

@ -42,15 +42,43 @@ pub enum FrameType {
}
impl WebsocketConnection {
pub async fn send_message(&self) -> io::Result<()> {
todo!()
pub async fn send_message(&mut self, frame_type: FrameType, data: &[u8]) -> io::Result<()> {
let mut header = Vec::with_capacity(14); // Max header size for 127-length payload
// First byte: FIN (1) + RSV1-3 (000) + opcode
let opcode = match frame_type {
FrameType::TextFrame => 0x1,
FrameType::BinaryFrame => 0x2,
FrameType::Ping => 0x9,
FrameType::Pong => 0xA,
FrameType::ConnectionClose => 0x8,
_ => panic!("No other type should by passed to this function"),
};
header.push(0b1000_0000 | opcode); // FIN = 1
// Second byte: MASK bit = 0 (server -> client frames are NOT masked)
let payload_len = data.len();
if payload_len < 126 {
header.push(payload_len as u8);
} else if payload_len <= u16::MAX as usize {
header.push(126);
header.extend_from_slice(&(payload_len as u16).to_be_bytes());
} else {
header.push(127);
header.extend_from_slice(&(payload_len as u64).to_be_bytes());
}
// Send header + payload
self.stream.write_all(&header).await?;
self.stream.write_all(data).await?;
self.stream.flush().await?;
Ok(())
}
pub async fn read_next_message(&mut self) -> io::Result<DataFrame> {
let first_line = self.parse_single_block().await?;
println!("Block read");
let mut data = first_line.data;
let frame_type = first_line.message_type;
@ -184,7 +212,7 @@ impl WebsocketConnection {
let result = hasher.finalize();
let result = BASE64_STANDARD.encode(result);
Response::new()
let rep = Response::new()
.with_code(crate::response::ResponseCode::SwitchingProtocols)
.with_header(crate::response::ResponseHeader::Upgrade(Upgrade {
protocol: Protocol::Websocket,
@ -196,11 +224,8 @@ impl WebsocketConnection {
.with_header(crate::response::ResponseHeader::Other {
header_name: "Sec-WebSocket-Accept".into(),
header_value: result.into(),
})
.respond(&mut stream)
.await?;
stream.flush().await?;
});
rep.respond(&mut stream).await?;
Ok(Self { stream })
} else {