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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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) {
        // Check erros
        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)]);

        // Check result of write
        match socket.write(request.as_bytes()) {
            Ok(n) => println!("Written {} lines", n),
            Err(e) => println!("Error sending data")
        }

        let mut buffer: String = String::new();

        // Check result of read
        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
    }
}