use std::net::TcpStream;
use std::io::{Result, Write, Read, BufReader, BufWriter};
use std::fmt::format;
const END_LINE: &str = "\r\n";
pub struct Client {
host: String,
port: u16,
path: String,
}
impl Client {
pub fn new(host: String, port: u16, path: String) -> Self {
Client { host, port, path }
}
fn generate_key(&self) -> String {
return String::from("dGhlIHNhbXBsZSBub25jZQ==");
}
fn handshake(&self) {
let mut socket = TcpStream::connect(format!("{}:{}", self.host, self.port.to_string())).unwrap();
let mut request = String::from(format!("GET {path} HTTP/1.1{end_line}", path = self.path, end_line = END_LINE));
request.extend([format!("host: {host}:{port}{end_line}", host = self.host, port = self.port, end_line = END_LINE)]);
request.extend([format!("connection: upgrade{}", END_LINE)]);
request.extend([format!("Upgrade: websocket{}", END_LINE)]);
request.extend([format!("sec-webSocket-Key: {key}{end_line}", key = self.generate_key(), end_line = END_LINE)]);
request.extend([format!("sec-webSocket-Version: 13{}", END_LINE)]);
request.extend([format!("user-agent: rust-esp32-std{}{}", END_LINE, END_LINE)]);
match socket.write(request.as_bytes()) {
Ok(n) => println!("Written {} lines", n),
Err(e) => println!("Error sending data")
}
let mut buffer: String = String::new();
match socket.read_to_string(&mut buffer) {
Ok(n) => println!("Readed {} lines", n),
Err(e) => println!("Error reading buffer")
}
println!("----------------- HANDSHAKE -----------------");
println!("{}\n", buffer);
buffer.clear();
socket.read_to_string(&mut buffer);
println!("{}", buffer);
}
pub fn connect(&self) -> bool {
self.handshake();
true
}
}