started the websocket communication
This commit is contained in:
parent
a4b1902fa5
commit
145cbb9243
3 changed files with 107 additions and 4 deletions
|
|
@ -3,17 +3,23 @@ use crate::{
|
|||
response::Response,
|
||||
};
|
||||
|
||||
use tokio::io;
|
||||
use tokio::io::{self, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use base64::prelude::*;
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
pub struct WebsocketConnection {
|
||||
stream: TcpStream,
|
||||
}
|
||||
|
||||
impl WebsocketConnection {
|
||||
pub fn initialize_connection(req: Request, stream: TcpStream) -> tokio::io::Result<Self> {
|
||||
pub async fn initialize_connection(
|
||||
req: Request,
|
||||
mut stream: TcpStream,
|
||||
) -> tokio::io::Result<Self> {
|
||||
let (mut upgrade, mut connection, mut key_exists) = (false, false, false);
|
||||
let mut key_val;
|
||||
let mut key_val: Box<str> = "".into();
|
||||
|
||||
for i in req.headers {
|
||||
match i {
|
||||
|
|
@ -32,15 +38,31 @@ impl WebsocketConnection {
|
|||
RequestHeader::Other { name, value } => {
|
||||
if name == "Sec-WebSocket-Key".into() {
|
||||
key_val = value.clone();
|
||||
key_exists = true;
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
if !upgrade || !connection || !key_exists {
|
||||
if upgrade && connection && key_exists {
|
||||
let magic_val = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(key_val.as_bytes());
|
||||
hasher.update(magic_val);
|
||||
|
||||
let result = hasher.finalize();
|
||||
let result = BASE64_STANDARD.encode(result);
|
||||
|
||||
Response::new().with_code(200).with_header(crate::response::ResponseHeader::Location)
|
||||
|
||||
Ok(Self { stream })
|
||||
} else {
|
||||
Response::new()
|
||||
.with_code(crate::response::ResponseCode::BadRequest)
|
||||
.respond(&mut stream)
|
||||
.await?;
|
||||
stream.flush().await?;
|
||||
Err(io::Error::new(io::ErrorKind::InvalidData, "Wrong request"))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue